[英]Use association properties with Entity Framework
I am just to set up a model in which you have news articles and topics they belong to. 我只是建立一个模型,在其中您将拥有新闻报道和新闻报道所属的主题。 This is a simple association but now it get's a bit "extended". 这是一个简单的关联,但是现在有点“扩展”了。 One of those topic association can be marked as the "mainTopic". 这些主题关联之一可以标记为“ mainTopic”。
I've set up 3 tables: 我已经设置了3张桌子:
avsn_content
, containing the newsArticles identified by id
avsn_content
,包含由id
标识的newsArticles
avsn_content_topics
, containing the assoc, having assocId
, id
, topicId
and a column indicating the mainTopic
avsn_content_topics
,包含assoc,具有assocId
, id
, topicId
和指示mainTopic
的列
avsn_topics
, containing the topic, identified by topicId
avsn_topics
,包含由topicId
标识的topicId
Furthermore, I have models for these three tables. 此外,我有这三个表的模型。 My association model is designed as follows: 我的关联模型设计如下:
[Table("avsn_content_topcis")]
public class TopicNewsModel
{
[Key]
[Column("assocId")]
public int Id { get; set; }
public NewsArticleModel NewsArticle { get; set; }
public TopicModel Topic { get; set; }
[Column("mainTopic")]
public bool IsMainTopic { get; set; }
}
My relationship setup looks like this: 我的关系设置如下所示:
modelBuilder.Entity<NewsArticleModel>()
.HasMany(x => x.Topics)
.WithMany()
.Map(m => m.MapLeftKey("id")
.MapRightKey("topicId")
.ToTable("avsn_content_topics"));
I am getting this error: 我收到此错误:
One or more validation errors were detected during model generation: 在模型生成期间检测到一个或多个验证错误:
NewsArticleModelTopicNewsModel: Name: The EntitySet 'NewsArticleModelTopicNewsModel' with schema 'dbo' and table 'avsn_content_topics' was already defined. NewsArticleModelTopicNewsModel:名称:具有模式“ dbo”和表“ avsn_content_topics”的实体集“ NewsArticleModelTopicNewsModel”已经定义。 Each EntitySet must refer to a unique schema and table. 每个EntitySet必须引用唯一的架构和表。
Removing the ToTable
option does not help it, so what am I doing wrong here? 删除ToTable
选项无济于事,所以我在这里做错了什么?
Well, found the answer right after posting this. 好吧,在发布此内容后立即找到答案。 Trying to pick the problem from the other end of the rope showed that I had to start off from the TopicNewsModel instead from the NewsModel. 试图从另一端找出问题,这表明我必须从TopicNewsModel开始,而不是从NewsModel开始。
modelBuilder.Entity<TopicNewsModel>()
.HasRequired(topicNews => topicNews.NewsArticle)
.WithMany(news => news.Topics)
.Map(m => m.MapKey("id"));
modelBuilder.Entity<TopicNewsModel>()
.HasRequired(topicNews => topicNews.Topic)
.WithMany()
.Map(m => m.MapKey("topicId"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.