entity framework - how to have multiple FK in the same table/class with EF4 Code first -
i have these 2 tables:
create table countries ( int id identity primary key, name nvarchar(20) ) create table persons ( int id identity primary key, country1 int references countries(id), country2 int references countries(id), country3 int references countries(id) )
how should create classes , mappings in order to map them correctly to these tables ? (i use ef4 ctp5 code first)
ignoring denormalized references multiple country entities now, write following:
public class country { [key] public int countryid { get; set; } [maxlength(20)] public string name { get; set; } } public class person { public int personid { get; set; } [maxlength(20)] public string name { get; set; } public country country1 { get; set; } public country country2 { get; set; } public country country3 { get; set; } }
of course, you'll need dbcontext:
public class context : dbcontext { public dbset<person> people { get; set; } public dbset<country> countries { get; set; } public context(string dbname) :base (dbname) { } }
this result in table schemas mirroring original requirement.
note, however, if declare classes this:
public class country { [key] public int countryid { get; set; } [maxlength(20)] public string name { get; set; } public icollection<person> people { get; set; } } public class person { public int personid { get; set; } [maxlength(20)] public string name { get; set; } public icollection<country> countries { get; set; } }
in case, ef create many-to-many join table allow associate number of countries number of people:
create table [countrypersons] ( [countrycountryid] int not null, [personpersonid] int not null );
note ef infers many-to-many relationship due collection of people in countries , collection of countries in people.
hth.
Comments
Post a Comment