简体   繁体   中英

Entity Framework code first one-to-many relationship

I'am trying to make a one-to-many relation through Request and Discussion tables. The fallowing code works fine but I want to make the Request.ID property to be foreign key instead of having a extra property like DiscussionId . I tried several ways but they all failed.

 public class Request
    {
        public int ID { get; set; }
        // other properties
        public int DiscussionId { get; set; }
        public virtual ICollection<Discussion> Discussion { get; set; }
    }

public class Discussion
    {
        public int ID { get; set; }
        public string Message { get; set; }
        public virtual Request Request { get; set; }
    }

As @Ghukas indicates, there's nothing requiring you to have DiscussionId as a property on your entity. In fact it's not really doing anything there. Request has a collection Discussion , but this is syntactic sugar, you don't actually even need that property if you don't want to access the discussions directly from your Request instance.

What actually creates the relationship is your Discussion.Request property. You did not specify an actual property to store the foreign key, but behind the scenes Entity Framework creates one for you, so on your dbo.Discussions table, you'll have a column named Request_ID , which will be used to hold this relationship. And, it will reference Request.ID automatically since that's the primary key of that table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM