2013-02-22 62 views
0

我公司所在地的一个简单的表结构和许多一对多CompanyLocation表,像这样:C#POCO许多一对多的关系,越来越Tablename_Fieldname

create table Company 
(
    CompanyId bigint not null identity, 
    CompanyName varchar(50), 
    --other fields 
    constraint PK_Company primary key (CompanyId) 
) 

create table Location 
(
    LocationId int not null identity, 
    LocationName varchar(50), 
    --other fields 
    constraint PK_Location primary key (LocationId) 
) 

create table CompanyLocation 
(
    CompanyId bigint not null, 
    LocationId int not null, 
    constraint PK_CompanyLocation primary key (CompanyId, LocationId), 
    constraint FK_CompanyLocation_Company foreign key (CompanyId) references Company(CompanyId), 
    constraint FK_CompanyLocation_Location foreign key (LocationId) references Location(LocationId) 
) 

所以我多对多表是一个“正确的”唯一键表。我的POCO类被定义为这样的:

public class Company 
{ 
    public long CompanyId { get; set; } 
    public string CompanyName { get; set; } 
    //more fields 

    public virtual List<Location> Locations { get; set; } 
} 

public class Location 
{ 
    public int LocationId { get; set; } 
    public string LocationName { get; set; } 
    //more fields 

    public virtual List<Company> Companies { get; set; } 
} 

它编译发现,当我运行它,在我加载一个公司,如果我访问Company.Locations.anything,我得到以下错误:

Invalid column name 'Location_LocationID'. 
Invalid column name 'Company_CompanyId'. 

我知道我可以手动映射这些,但我正在尝试遵循Convention Over Configuration Entity Framework创建POCO多对多关系的方式。我对这个模型做了什么错误?

-shnar

回答

0

你需要有与Location_LocationID & Company_CompanyId领域连接表,以便采取的EF公约的优势。虽然我没有设法通过Fluent API映射来启动并运行,但我尝试过并且遇到了同样的错误,例如EF忽略了我的Fluent API映射。

问候

+0

好了,我的表有外键彼此,我以为EF只是应该“知道”,并为我们做这种映射,按照惯例?我通过手动强制并在位置列表上方放置了[ForeignKey(“LocationId”)]属性来实现这一目标,但是我认为如果我们遵循EF的约定,我们不必这么做? – shnar 2013-08-22 23:28:04