我有这些课程:
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; }
}
现在每个contenttype都有一个父级和一个子级列表。如何使用ef5在模型和上下文中定义它?
答案 0 :(得分:3)
如果您希望您的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);
}
你去吧..
答案 1 :(得分:2)
您的父母和内容类型表(1 - 多(*))
public class Parent
{
public int Id { get; set; }
//other properties in parent class....
public virtual ICollection<ContentType> ContentTypes { get; set; }
}
public class ContentType
{
public int Id { get; set; }
//other properties...
public int ParentId { get; set; }//..this will help us to define the relationship in fluent API
public Parent Parent { get; set; }
}
在您的DBContext类中..
public DbSet<Parent> Parents { get; set; }
public DbSet<ContentType> ContentTypes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ContentType>().HasRequired(c => c.Parent).WithMany(p =>p.ContentTypes).HasForeignKey(c => c.ParentId);
}
以同样的方式,您可以让ContentType
作为父级列表的父级列表。
您也可以查看此link。我希望它现在有所帮助。 :)
答案 2 :(得分:1)
我假设您的孩子和父母属于ContentType类型?
如果是这样,在基类ContentType中添加属性:
public virtual ICollection<ContentType> Children {get;set;}
public virtual Content Type Parent {get;set;}
然后通过例如modelBuilder [ref:http://msdn.microsoft.com/en-us/data/jj591620.aspx]或通过EntityTypeConfiguration [ref:http://msdn.microsoft.com/en-us/library/gg696117(v=vs.113).aspx]
映射链接基本上它和你要做的任何其他关系一样。