1

我有这两张桌子:

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)
)

我应该如何创建我的类和映射以便将它们正确映射到这些表?(我首先使用 EF4 CTP5 代码)

4

1 回答 1

2

现在忽略您对多个国家实体的非规范化引用,您可以编写以下内容:

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; }
}

当然,您还需要 DbContext:

public class Context : DbContext
{
    public DbSet<Person> People { get; set; }
    public DbSet<Country> Countries { get; set; }

    public Context(string dbName)
        :base (dbName)
    {
    }
}

这将导致表模式反映您的原始要求。

但是请注意,如果您这样声明类:

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; }
}

在这种情况下,EF 将创建一个多对多连接表,允许您将任意数量的国家与任意数量的人关联起来:

CREATE TABLE [CountryPersons] 
(
    [CountryCountryID] int NOT NULL,
    [PersonPersonID] int NOT NULL
);

请注意,EF 推断多对多关系是由于 People in countries 的集合和 Country in People 的集合。

HTH。

于 2011-02-24T09:59:29.130 回答