我将Code First与Entity Framework 5一起使用。
我有User
课程,其中一个用户可以成为很多人的朋友。
public class User
{
[Key]
public Guid UserID { get; set; }
public virtual ICollection<User> Friends { get; set; }
}
但这会映射0..1对多。我应该如何在Code First中与同一个类映射多对多关系?
答案 0 :(得分:1)
添加配置类:
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);
}
}
答案 1 :(得分:0)
public class Organization : Entity
{
public string Name { get; set; }
public string Description { get; set; }
public virtual Organization Parent { get; set; }
public virtual ICollection<Organization> Children { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class OrganizationConfiguration : EntityMapperBase<Organization>
{
public OrganizationConfiguration()
{
HasKey(f => f.Id);
Property(f => f.Name).HasMaxLength(20).IsRequired();
HasMany(f => f.Children).WithOptional(f => f.Parent).Map(m => m.MapKey("ParentId")).WillCascadeOnDelete(false);
HasMany(f => f.Users).WithRequired(f => f.Organization).Map(m => m.MapKey("OrganizationId"));
}
}
可能对你有所帮助
答案 2 :(得分:-1)
你应该有两个导航属性
public class User
{
[Key]
public Guid UserID { get; set; }
public virtual ICollection<User> FriendsOfMine { get; set; }
public virtual ICollection<User> FriendsWithMe { get; set; }
}