cecemel
cecemel

Reputation: 636

How to create a one to many relationship using ADO.NET Entity Framework Code First?

I am struggling with an issue and from what I've seen none of the propsed solutions work.

Basically I have two classes:

public class Role
{
    [Key]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

public class ActionType
{
    public int ID { get; set;}
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Role> AllowedRoles { get; set; }

    public ActionType()
    {
        this.AllowedRoles = new List<Role>();
    }  
}

I would like for EF to force an association table in the DB, where the FK is used to reference the one to many relation. Somehow code first creates a table for my Role where a column ActionType_ID is added. Not useful of course when more Roles are added to one ActionType. A DBUpdateExcpetion is being trown.

Any thoughts on how I should resolve this? The point being that classe Role doesn't refer to ActionType, since this is not useful.

Thank you!

Upvotes: 2

Views: 1218

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

What are you really trying to do? At the moment you can add more Roles to single ActionType but single Role cannot be added to multiple ActionTypes. Do you want that as well?

In such case you are not doing one-to-many association but many-to-many. Only many-to-many relation uses junction (association) table. One-to-many relation indeed means that dependent entity (the one on many side) has FK to principal entity. The simplest approach is defining navigation property in Role as well:

public class Role
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<ActionType> ActionTypes { get; set; } 
}

public class ActionType
{
    public int ID { get; set;}
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Role> AllowedRoles { get; set; } 
}

If you don't want to have navigation property in Role you must use fluent API to describe the relation.

public class Context : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ActionType>()
                    .HasMany(a => a.AllowedRoles)
                    .WithMany();
    }
}

Upvotes: 1

Related Questions