我有这些课:
public class ContentType
{
public int ContentTypeId{get;set;}
public string Name{get;set;}
public int Lang{get;set;}
public bool IsPublished{get;set;}
public int? ParentId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}
public class Context : DbContext
{
public Context()
{
base.Configuration.LazyLoadingEnabled = false;
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.ValidateOnSaveEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<ContentType> ContentTypes { get; set; }
}
现在,每个内容类型都有一个父级和一个子级列表。如何使用ef5在模型和上下文中定义它?
最佳答案
如果您希望您的contenttype类有子级,请使用以下代码:
public class ContentType
{
///other properties
public ContentType Parent { get; set; }
public int? ParentId { get; set; }
public ICollection<ContentType> Childern { get; set; }
}
并像这样映射:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContentType>()
.HasMany(c => c.Children)
.WithOptional(c => c.Parent)
.HasForeignKey(c => c.ParentId);
base.OnModelCreating(modelBuilder);
}
你去那里..
关于c# - 在ef5中与自己有多对多关系?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20727947/