c# - how to use entity framework code first the mapping about one to one -
all,i have question don't know how use entity framework code frist. have 2 table tba , tbb
create table tba ( [id] int not null identity(1,1) constraint [pk_tba] primary key, [name] varchar(50) not null ) create table tbb ( [id] int not null identity(1,1) constraint [pk_tbb] primary key, [name] varchar(50) not null, [tbaid] int not null )
in database don't have use forgin key.
this code,i don't know how mapping looks 1 one relationship
class program { static void main(string[] args) { string connectionstring = "data source=localhost;database=demo;integrated security=true"; mydbcontext db = new mydbcontext(connectionstring); db.tba.asparallel().forall(x => { console.writeline("{0}----{1}", x.tbaid, x.tbaname); }); //here throw error db.tbb.asparallel().forall(x => { console.writeline("{0}--{1}--{2}--{3}", x.tbbid, x.tbbname, x.mytba.tbaid, x.mytba.tbaname); }); console.readline(); } } public class mydbcontext : dbcontext { public dbset<tba> tba { get; set; } public dbset<tbb> tbb { get; set; } public mydbcontext(string connectionstring) : base(connectionstring) { } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.configurations.add(new tbamapping()); modelbuilder.configurations.add(new tbbmapping()); base.onmodelcreating(modelbuilder); } } public class tba { public int tbaid { get; set; } public string tbaname { get; set; } } public class tbb { public int tbbid { get; set; } public string tbbname { get; set; } public tba mytba { get; set; } } public class tbamapping : entitytypeconfiguration<tba> { public tbamapping() { totable("tba"); haskey(x => x.tbaid); property(x => x.tbaid).isrequired().hascolumnname("id"); property(x => x.tbaname).isrequired().hascolumnname("name"); } } public class tbbmapping : entitytypeconfiguration<tbb> { public tbbmapping() { totable("tbb"); haskey(x => x.tbbid); property(x => x.tbbid).isrequired().hascolumnname("id"); property(x => x.tbbname).isrequired().hascolumnname("name"); // here, how setting mapping tba.id here } }
first of must declare tba mytba virtual,
public virtual tba mytba{get;set;}
(*)public int tbaid{get;set;}
then can configure relations on typeconfiguration.
need foreignkeytoa in b class.(*)
hasrequired(x=>x.mytba).withoptional().hasforeignkey(x=>x.foreignkeytoa);
if put
.withoptional(empty).
thas tell entity class has not foreign key b.
Comments
Post a Comment