Saeid
Saeid

Reputation: 13582

Define 2 Foreign Key in Model of MVC EntityFrameWork Code First

I Have a Phone Book With a Share table and a Member table The share table must have 2 FK to Member table one as a owner and another as a Joint Member but I can not Model it truly:

This is My DB Model:

public class PhoneBookDB : DbContext {

    public DbSet<Member> Members { get; set; }
    public DbSet<ContactKind> ContactKinds { get; set; }
    public DbSet<Contact> Contacts { get; set; }
    public DbSet<NumberKind> NumberKinds { get; set; }
    public DbSet<Number> Numbers { get; set; }
    public DbSet<AddressKind> AddressKinds { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<City> Cities { get; set; }
    public DbSet<Group> Groups { get; set; }
    public DbSet<ShareAccess> ShareAccesses { get; set; }
    public DbSet<Share> Shares { get; set; }

}

This is the Model of Share:

public class Share {

    public long Id { get; set; }
    public Group Group { get; set; }
    public ShareAccess ShareAccess { get; set; }
    public Member Owner { get; set; }
    public Member JointMember { get; set; }

}

And This is the Model of Member:

public class Member {

    public long Id { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<Group> Groups { get; set; }
    public virtual ICollection<Share> OwnerShares { get; set; }
    public virtual ICollection<Share> JointShares { get; set; }
    public virtual ICollection<NumberKind> NumberKinds { get; set; }
    public virtual ICollection<AddressKind> AddressKinds { get; set; }
}

with this design of models I have 4 FK in share table to member table at DB, And Also I cant Access to share elements by Member Model

Like this:

db.Members.Single(m => m.Shares.Any(sh => sh.Id == item.Id))

or this one:

db.Shares.Single(sh => sh.Id == item.Id).JointMember

but both of them return Null.

I try more version of models like: one ICollection in Member or one Member prop in Share Model but none of them give me a true DB tables and answer. Also I need atleast one Collection of share in Member Model for retrieve shares element by member, as you know I coded by EFCodeFirst And I need a way to solve this problem, Thank you

Upvotes: 0

Views: 1322

Answers (1)

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

You need o define he relaionships in OnModelCreating event of your DbContext like this,

    modelBuilder.Entity<Share>().
HasRequired(s=>s.Owner ).WithMany(p=>p.OwnerShares).WillCascadeOnDelete(false);

    modelBuilder.Entity<Share>().HasRequired(s=>s.JointMember )
.WithMany(p=>p.JointShares );

I think in the same way you may be need to define other relationships(ShareAccess ,Group) also. Here is a good tutorial to start with, http://blogs.msdn.com/b/adonet/archive/2010/12/06/ef-feature-ctp5-fluent-api-samples.aspx

Upvotes: 1

Related Questions