Fluent API, EF 4.1: a problem of inheritance and foreign key

百般思念 提交于 2019-12-13 00:14:13

问题


There are several simple classes:

The first class:

public class User
{
   public int UserId { get; set; }
   public string Username { get; set; }

   // ...

   public ICollection<Topic> Topics { get; set; }
}

The second class:

public class Publication 
{
   public int PublicationId { get; set; }
   public string Title { get; set; }

   / ...

   public User Author { get; set; }
}

The third class:

public class Topic: Publication 
{
   public string TopicContent { get; set; }

   // ...
}

After creating a database for my model I have the following stucture of the database:

Users

UserId

UserName

Publications

PublicationId

Title

TopicContent

Author_UserId

User_UserId

As you can see I get two fields Author_UserId and User_UserId having identical role in the table Publications.

How can I merge this fields into one field using Fluent API or Data Annotation?


回答1:


I don't think that it's possible to have the same foreign key column in the Publications table. Publication.Author and User.Topics cannot be the endpoints of one and the same association. You could have a Publication instance which isn't a Topic and a reference to a User:

User user = new User() { Topics = new List<Topic>() };
Publication publication = new Publication();

publication.Author = user;

user.Topics.Add(???);

At ??? you can't add publication because it isn't a Topic instance. user.Topics must refer to another object than publication which means that those endpoints cannot belong to the same association.

Edit

If you want only one single association with only a single foreign key column in the database you must either move the Author property from Publication to Topic or let the collection in your User class refer to Publication instead of Topic:

public ICollection<Publication> Publications { get; set; }


来源:https://stackoverflow.com/questions/5674729/fluent-api-ef-4-1-a-problem-of-inheritance-and-foreign-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!