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 I create my classes and mappings in order to map them correctly to to these table开发者_运维知识库s ? (I use EF4 CTP5 Code First)
Ignoring your denormalized references to multiple country entities for now, you could write the 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 also need the DbContext:
public class Context : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Country> Countries { get; set; }
public Context(string dbName)
:base (dbName)
{
}
}
This will result in the table schemas mirroring your original requirement.
Note, however, that if you declare the classes like 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 this case, EF will create a many-to-many join table which will allow you to associate any number of countries with any number of people:
CREATE TABLE [CountryPersons]
(
[CountryCountryID] int NOT NULL,
[PersonPersonID] int NOT NULL
);
Note that EF infers the many-to-many relationship due to the collection of People in Countries and collection of Countries in People.
HTH.
精彩评论