I'm using EntityFramework version 5.0 in WinForms project, .net 4.5.
I have created 2 for me important Entities
public class Role
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public bool StockPermission { get; set; }
public bool ItemPermission { get; set; }
public bool OrderPermission { get; set; }
public bool PersonPermission { get; set; }
public bool StatisticPermission { get; set; }
}
public class Person
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public String Name { get; set; }
public String Nickname { get; set; }
public String Contact { get; set; }
public System.DateTime Created { get; set; }
public String Pincode { get; set; }
public virtual ICollection<Role> Role { get; set; }
public virtual Person Creator { get; set; }
}
and dbContext class:
public class SusibarDbContext : DbContext
{
public DbSet<Entity.Role> Roles { get; set; }
public DbSet<Entity.Person> Persons { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//base.OnModelCreating(modelBuilder);
}
}
please, can you help me what I need to add into OnModelCreating(DbModelBuilder modelBuilder)
function to define relations between Person and Role?
Person can have many Role(s) (but can't be null), different Persons can have same Role(s).
Person can have one "creator" Person (can be null), different Persons can have same "creator"
If you could be so kind, just advise me solution :-(
If you want to use Fluent API for it, look at this topic from MSDN. You should use Many-to-Many relationship and EF will create a table required for case when Person can have many Roles and Role have many Persons. Something like this:
modelBuilder.Entity<Person>().HasMany(x => x.Roles).WithMany();
Also you can create this relationship without using Fluent API. You should create navigation property ICollection<Person> Persons
in Role class and EF will create appropriate table and relationship as well.