The*_*Sky 9 c# entity-framework poco code-first entity-framework-4
您如何在EF4 Code-First CTP3中表示多对多关系?
例如,如果我有以下类:
class User
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Profile> Profiles { get; set; }
}
class Profile
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在数据库中有一个UserProfiles表,其中包含FK for User和FK for Profile.我该如何映射?
编辑:我知道如何当前地图上有一个ICollection<User>
属性Profile
,但我真的不希望有一个相反的导航属性应该是"用户有很多配置文件".
编辑:CTP4昨天(2010年7月14日)发布,现在支持:
modelBuilder.Entity<Post>().HasMany(p => p.Tags).WithMany();
我终于发现目前这是不可能的.Microsoft正在寻求添加此功能(仅一个导航属性).
有关详细信息,请参阅MSDN论坛上的此链接:http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/6920db2b-88c7-4bea-ac89-4809882cff8f
对于多对多关系,您应该在两侧包含导航属性并使其成为虚拟(以利用延迟加载)
class User
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Profile> Profiles { get; set; }
}
class Profile
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> Users { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后使用该设置,您可以定义多对多关系(您也可以让实体框架为您执行此操作,但我不喜欢它使用的命名约定.)
modelBuilder.Entity<Profile>().
HasMany(p => p.Users).
WithMany(g => g.Profiles).
Map(t => t.MapLeftKey("ProfileID")
.MapRightKey("UserID")
.ToTable("UserProfiles"));
Run Code Online (Sandbox Code Playgroud)
这将为您提供一个名为UserProfiles的表,其中UserID和ProfileID为Keys.
归档时间: |
|
查看次数: |
4130 次 |
最近记录: |