gaurav bhavsar
gaurav bhavsar

Reputation: 2043

Entity Relationship mapping using EntityFramework Code First Approch

I am creating bug tracker application and stuck at mapping.

User Entity :

public class User : Entity {
    public IList<Issue> Assignees { get; set; }
    public IList<Issue> Authors { get; set; }
}

Issue Entity :

public class Issue : SoftDeletableEntity {
    public User Author { get; set; }
    public long AuthorID { get; set; }

    public User Assignee { get; set; }
    public long AssigneeID { get; set; }
}

Now, when I add migration, a snapshot of current Code First model is :

CreateTable(
            "dbo.Issue",
            c => new {
                ID = c.Long(nullable: false, identity: true),
                AuthorID = c.Long(nullable: false),
                AssigneeID = c.Long(nullable: false),
                DeletedBy = c.String(),
                DeletedOn = c.DateTime(),
                IsDeleted = c.Boolean(nullable: false),
                Name = c.String(),
                CreatedOn = c.DateTime(nullable: false),
                ModifiedOn = c.DateTime(nullable: false),
                User_ID = c.Long(),
                User_ID1 = c.Long(),
            })
            .PrimaryKey(t => t.ID)
            .ForeignKey("dbo.User", t => t.AssigneeID, cascadeDelete: false)
            .ForeignKey("dbo.User", t => t.AuthorID, cascadeDelete: false)
            .ForeignKey("dbo.User", t => t.User_ID)
            .ForeignKey("dbo.User", t => t.User_ID1)
            .Index(t => t.AuthorID)
            .Index(t => t.AssigneeID)
            .Index(t => t.User_ID)
            .Index(t => t.User_ID1);

above Migration created AuthorID and AssigneeID and also added User_ID and User_ID1, since I added below properties into User table.

public IList<Issue> Assignees { get; set; }
public IList<Issue> Authors { get; set; }

Its created this User_ID and User_ID1 but I require to mapped with AuthorID and AssigneeID.

Note : I am using EntityFramework 6.0

Let me know how I can achieve above things and giude me if I am doing anything wrong.

Thanks In Advance

Upvotes: 1

Views: 23

Answers (1)

Anuj Pandey
Anuj Pandey

Reputation: 938

add this to your data context that should solve your issue.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<Issue>()
         .HasMany(x => x.Authors)
         .WithRequired(x => x.Author)
         .HasForeignKey(x => x.AuthorID);
    modelBuilder.Entity<Issue>()
         .HasMany(x => x.Assignees)
         .WithRequired(x => x.Assignee)
         HasForeignKey(x => x.AssigneeID);
}

Upvotes: 2

Related Questions