问题描述
有几个简单的类:
第一类:
public class User
{
public int UserId {get;组; }
public string Username {get;组; }
// ...
public ICollection<主题>主题{get;组;
}
第二类:
public class Publication
{
public int PublicationId {get;组; }
public string标题{get;组; }
/ ...
public User Author {get;组;
}
第三类:
public class主题:出版物
{
public string TopicContent {get;组; }
// ...
}
创建后一个我的模型的数据库我有以下数据库的结构:
用户
UserId
UserName
出版物
PublicationId
标题
主题内容
Author_UserId
User_UserId
正如你所看到的,我得到两个字段Author_UserId和User_UserId具有相同的
如何使用Fluent API或数据注释将此字段合并到一个字段?
我不认为在出版物
表中可以有相同的外键列。 Publication.Author
和 User.Topics
不能是同一个关联的端点。您可能有一个发布
实例,它不是主题
,并引用用户
:
User user = new User(){Topics = new List< Topic>() ;
出版刊物= new Publication();
publication.Author = user;
user.Topics.Add(???);
在???您不能添加发布
,因为它不是主题
实例。 user.Topics
必须引用另一个对象,而不是 publication
,这意味着这些端点不能属于同一个关联。 p>
修改
如果您只想要一个关联,只有一个外键列在数据库中,您必须将作者
属性从出版物
移动到主题
或让您的用户
类中的集合引用发布
而不是主题
:
public ICollection< Publication>出版物{get;组; }
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?
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; }
这篇关于流利的API,EF 4.1:继承和外键的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!