[英]1 to many relation to itself in ef5?
我有这些课:
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);
}
你去那里..
您的父母和内容类型表(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
类充当具有一系列子代的父代。 您也可以查看此链接 。希望现在对您有所帮助。 :)
我假设您的孩子和父母的类型都是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-我们/图书馆/gg696117(v=vs.113).aspx ]
基本上,它与您将执行的任何其他关系相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.