Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I need to add into OnModelCreating(DbModelBuilder modelBuilder) function to define relations between Person and Role?

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 :-(

like image 795
eCorke Avatar asked Dec 07 '12 00:12

eCorke


People also ask

What is OnModelCreating method?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.

Which method is used to apply configuration to entities or their properties in the Entity Framework Core?

Property Mapping. The Property method is used to configure attributes for each property belonging to an entity or complex type.

What is a ModelBuilder in Entity Framework Core?

In Entity Framework Core, the ModelBuilder class acts as a Fluent API. By using it, we can configure many different things, as it provides more configuration options than data annotation attributes.

What is DbModelBuilder in C#?

DbModelBuilder is used to map CLR classes to a database schema. This code centric approach to building an Entity Data Model (EDM) model is known as 'Code First'.


3 Answers

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.

like image 199
klappvisor Avatar answered Oct 13 '22 21:10

klappvisor


Something like this should do the job:

Create a POCO called PersonRole. This is intended to model the relationship between a Person and a Role.

public class PersonRole
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public Person Person { get; set; }
    public Role Role { get; set; }
}

In the Person class, replace:

public virtual ICollection<Role> Role { get; set; }

with:

public virtual ICollection<PersonRole> PersonRoles { get; set; }

If you want to, you could add the following to the Role class:

public virtual ICollection<PersonRole> PersonRoles { get; set; }

doing so is optional, though it may be useful if you are wishing to look at all People with a particual Role.

In the OnModelCreating method, use this code to ensure that a PersonRole will enforce non-nullable Person and Role properties.

modelBuilder.Entity<PersonRole>().HasRequired(p => p.Person);
modelBuilder.Entity<PersonRole>().HasRequired(p => p.Role);

Edit:

The reason for creating the PersonRole POCO is to ensure that a Role can be reused across different users. Using the existing public virtual ICollection<Role> Role { get; set; } will work, but it will probably not work as intended.

With the relationship public virtual ICollection<Role> Role { get; set; }, what EF is going to do is augment the Role table with an additional field, e.g., PersonId, which will be used to relate a Person to their Roles. The problem with this is clear: without the linking PersonRole table, you won't be able to give two people the same Role.

like image 45
nick_w Avatar answered Oct 13 '22 21:10

nick_w


Although not an answer to your question directly, use EF naming conventions to avoid Annotaions and keep your entity classes clean. I will demonstrate 2 situations:

One - Many using EF Naming Convention

Role has Many Persons, Person has one Role

One - Many Where No Naming convention Exists (Parent-Child of same Type)

Person has many Created, Person has one Creator)

public class Role
{
    public int RoleId { get; set; }
    public string Name { get; set; }
    ...

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
    public int PersonId { get; set; }
    public int CreatorId { get; set; } 
    public int RoleId { get; set; } 
    ...

    public virtual Role Role { get; set; }
    public virtual Person Creator { get; set; }
    public virtual ICollection<Person> Created { get; set; }
}

For the Creator-Created relationship in OnModelCreating:

modelBuilder.Entity<Person>()
    .HasOptional(p => p.Creator)
    .WithMany(p => p.Created)
    .HasForeignKey(p => p.CreatorId);

With, "ClassName" + "Id" (case sensitive), EF will assume that it is the Primary Key / Identifier automatically. The Role-Person relationship will be created automatically due to the Virtual Mapping combined with the PrimaryKey "RoleId"

like image 1
Talon Avatar answered Oct 13 '22 21:10

Talon