Entity framework 如何先用代码将多对多映射到同一类?
我首先使用实体框架5的代码 我有Entity framework 如何先用代码将多对多映射到同一类?,entity-framework,ef-code-first,Entity Framework,Ef Code First,我首先使用实体框架5的代码 我有User类,其中一个用户可以与许多人成为朋友 public class User { [Key] public Guid UserID { get; set; } public virtual ICollection<User> Friends { get; set; } } 公共类用户 { [关键] 公共Guid用户标识{get;set;} 公共虚拟ICollection好友{get;set;} } 然而,这将0..1映射
User
类,其中一个用户可以与许多人成为朋友
public class User
{
[Key]
public Guid UserID { get; set; }
public virtual ICollection<User> Friends { get; set; }
}
公共类用户
{
[关键]
公共Guid用户标识{get;set;}
公共虚拟ICollection好友{get;set;}
}
然而,这将0..1映射到多。如何首先在代码中映射同一类的多对多关系?您应该有两个导航属性
public class User
{
[Key]
public Guid UserID { get; set; }
public virtual ICollection<User> FriendsOfMine { get; set; }
public virtual ICollection<User> FriendsWithMe { get; set; }
}
公共类用户
{
[关键]
公共Guid用户标识{get;set;}
公共虚拟ICollection FriendsOfMine{get;set;}
公共虚拟ICollection Friends{get;set;}
}
公共类组织:实体
{
公共字符串名称{get;set;}
公共字符串说明{get;set;}
公共虚拟组织父级{get;set;}
公共虚拟ICollection子项{get;set;}
公共虚拟ICollection用户{get;set;}
}
公共类组织配置:EntityMapperBase
{
公共组织配置()
{
HasKey(f=>f.Id);
属性(f=>f.Name).HasMaxLength(20.IsRequired();
有许多(f=>f.Children)。带有可选(f=>f.Parent)。映射(m=>m.MapKey(“ParentId”)。将级联删除(false);
有许多(f=>f.Users).WithRequired(f=>f.Organization).Map(m=>m.MapKey(“OrganizationId”);
}
}
它可以帮助您添加配置类:
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
HasMany(u => u.Friends).WithMany();
}
}
public class UserConfiguration : EntityTypeConfiguration<User>
{
public UserConfiguration()
{
HasMany(u => u.Friends).WithMany();
}
}
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new UserConfiguration());
base.OnModelCreating(modelBuilder);
}
}