EF代码第一:多对多和一对多 [英] EF Code First: Many-to-many and one-to-many
问题描述
这可能只是因为我缺乏EF Code First流利的API的知识,但我很累。
This is probably just because my knowledge with the EF Code First fluent API is lacking, but I'm stumped.
我想建模如下:
- 群组集合(含ID和名称)
- 的集合
- 每个用户只分配给一个主组
- 每个用户可能有零个或多个次组
- A Groups collection with Id and Name
- A Users collection with Id and Name
- Each user is assigned to exactly one primary group
- Each user may have zero or many secondary groups
我要使用的表结构如下:
The table structure I'm going for would look like:
strong>群组
Groups
- Id
- 姓名
使用者
-
- 姓名
- PrimaryGroupId
SecondaryGroupAssignments
- UserId
- GroupId
我一直在对着墙试图用EF Code First建模,但我不能让它接受用户和组之间的关系。对不起,没有发布任何.NET代码(我很高兴),但它可能都是错误无论如何。
I've been beating my head against a wall trying to model this with EF Code First, but I can't get it to accept both relationships between User and Group. Sorry for not posting any .NET code (I'm happy to), but it's probably all wrong anyway.
有没有办法使EF模型?我假设我必须用Fluent API做一些配置。也许一个更好的问题是:有没有任何好的,明确的参考为Fluent API?
Is there a way to make EF model this? I'm assuming I have to do some sort of configuration with the Fluent API. Maybe a better question is: is there any good, definitive reference for the Fluent API?
谢谢!
推荐答案
尝试这个(未测试的):
Try this (untested):
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<User> PrimaryUsers { get; set; }
public virtual ICollection<User> SecondaryUsers { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int PrimaryGroupId { get; set; }
public virtual Group PrimaryGroup { get; set; }
public virtual ICollection<Group> SecondaryGroups { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Group> Groups { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<User>()
.HasRequired(u => u.PrimaryGroup)
.WithMany(g => g.PrimaryUsers)
.HasForeignKey(u => u.PrimaryGroupId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<User>()
.HasMany(u => u.SecondaryGroups)
.WithMany(g => g.SecondaryUsers)
.Map(m => m.MapLeftKey("UserId")
.MapRightKey("GroupId")
.ToTable("SecondaryGroupAssignments"));
}
}
这篇关于EF代码第一:多对多和一对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!