Reputation: 2975
I have these classes:
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; }
}
Now every contenttype has a parent and a list of childrens. How to define this in the model and Context with ef5?
Upvotes: 1
Views: 99
Reputation: 1746
Your Parent and Content Type Table (1 - many (*))
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; }
}
In your DBContext Class..
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);
}
In the same way you can have ContentType
class acting as parent with a list of children.
You can also check out this link.I hope it helps now. :)
Upvotes: 2
Reputation: 3473
I assume you the children and parent are of type ContentType?
If so, in the base class ContentType add properties:
public virtual ICollection<ContentType> Children {get;set;}
public virtual Content Type Parent {get;set;}
Then map the links via for example the modelBuilder [ ref: http://msdn.microsoft.com/en-us/data/jj591620.aspx ] or via EntityTypeConfiguration [ ref: http://msdn.microsoft.com/en-us/library/gg696117(v=vs.113).aspx ]
Basically it's the same as any other relation you would do.
Upvotes: 1
Reputation: 1952
if you want your contenttype class to have children use this code:
public class ContentType
{
///other properties
public ContentType Parent { get; set; }
public int? ParentId { get; set; }
public ICollection<ContentType> Childern { get; set; }
}
and map that like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContentType>()
.HasMany(c => c.Children)
.WithOptional(c => c.Parent)
.HasForeignKey(c => c.ParentId);
base.OnModelCreating(modelBuilder);
}
there you go..
Upvotes: 3