【发布时间】:2011-12-09 08:28:40
【问题描述】:
我想仅使用数据注释来映射多对可能的关系,所以这是我的情况。
假设我有下表
Foo:
FooId int identity
FooName varchar(max) not null
Bar:
BarId int identity
BarName varchar(max) not null
FooBarRelationships
TheBarId int
TheFooId int
如您所见,联结表包含与源不同的 FK 名称。另外表名也不同
我的课如下
[Table("Foo")]
public class Foo {
[Key]
public Int32 FooId { get; set; }
public String FooName { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
[Table("Bar")]
public class Bar {
[Key]
public Int32 BarId { get; set; }
public String BarName { get; set; }
public IEnumerable<Foo> Foos { get; set; }
}
我应该如何使用数据注释修改我的类,以便告诉表 FooBarRelationships 是联结表,TheBarId 是来自 Bar 表的外键,TheFooId 是来自 @987654327 的外键@桌子?
附言
将导航属性声明为IEnumerable<T>,而不是ICollection<T> 是必不可少的。
我尝试使用如下所示的地图类对其进行映射
public class BarMap : EntityTypeConfiguration<Bar> {
public BarMap() {
this.HasMany(t => t.Foos)
.WithMany(t => t.Bars)
.Map(m => {
m.ToTable("FooBarRelationships");
m.MapLeftKey("TheBarId");
m.MapRightKey("TheFooId");
});
}
}
这给了我以下错误。
方法 'System.Data.Entity.ModelConfiguration.EntityTypeConfiguration
.HasMany (System.Linq.Expressions.Expression >>)' 的类型参数不能从用法推断。尝试明确指定类型参数。
如果有办法在不将类型IEnumeralbe<T> 更改为ICollection<T> 的情况下解决此错误,也欢迎。
【问题讨论】:
标签: c# entity-framework-4.1 many-to-many data-annotations code-first