我真的希望你能帮助我,因为我刚刚将我的MVC / Entity Framework项目放在bin中,并启动了一个MVC / Linq项目。
我正在建立一个论坛作为一个项目,以了解MVC / Entity,并且我有4个表都是相关的。
Forum_Category, 论坛, 话题, 回复因此Forum_Category和Forum之间的Category_ID有1到多个。
论坛与主题之间的Forum_ID为1到很多。
Topic和Reply之间的Topic_ID为1到多个。
我知道你可以使用加载相关数据
Dim F = (From forum in _DataContext.Forum.Include("Forum_Category") _ Where forum.Forum_ID = 1 _ Select forum).First但是如果我想要获得所有单个主题回复的数据,那么请加载主题的论坛,然后加载类别?
我设法在代码中稍微得到一点:
Dim FT = (From F In _dataContext.Topic.Include("Forum") _ Where F.TOPIC_STATUS = ForumSettings.FORUM_STATUS.Active _ Select F).First() Dim TRs = (From F In _dataContext.Topic_Reply _ Where F.Topic.TOPIC_ID = TopicID _ Select F).ToList() For Each TR As Topic_Reply In TRs FT.Topic_Reply.Add(TR) Next Return FT但是,当我试图添加一个新的回复时,我得到了错误:ObjectStateManager中已存在具有相同关键字的对象。 ObjectStateManager不能使用同一个键跟踪多个对象。
我现在完全失去了。
I really hope you can help me as I am about to just throw my MVC/Entity Framework project in the bin and start a MVC/Linq project.
I am building a forum as a project just to get to know MVC/Entity, and I have 4 tables which are all related.
Forum_Category, Forum, Topic, Replyso there is a 1 to many on Category_ID between Forum_Category and Forum.
1 to many on Forum_ID between forum and topic.
and a 1 to many on Topic_ID between Topic and Reply.
I understand that you can load up related data using
Dim F = (From forum in _DataContext.Forum.Include("Forum_Category") _ Where forum.Forum_ID = 1 _ Select forum).Firstbut what if I wanted to get the data for all the replys to a single topic, then load up the topic's forum and then the category?
I managed to get slightly there with the code:
Dim FT = (From F In _dataContext.Topic.Include("Forum") _ Where F.TOPIC_STATUS = ForumSettings.FORUM_STATUS.Active _ Select F).First() Dim TRs = (From F In _dataContext.Topic_Reply _ Where F.Topic.TOPIC_ID = TopicID _ Select F).ToList() For Each TR As Topic_Reply In TRs FT.Topic_Reply.Add(TR) Next Return FTBut then when I tried to add a new Reply, I got the error: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
I am totally lost now.
最满意答案
Dim FT = (From T In _dataContext.Topic.Include("Replies").Include("Forum") _ Where T.TOPIC_ID = TopicID _ Select T).First()......假设该房产被称为“回复”而不是“回复”。 :)
现在你可以看FT.Replies看到答复和FT.Forum来看论坛。
不要使用Add。 那是对你的数据库进行INSERT,当然那些记录已经在那里了。 这就是错误的含义。
这里关键的洞察是所有的关系都是双向的。 您可以从关系的任一侧看到相关对象。
Dim FT = (From T In _dataContext.Topic.Include("Replies").Include("Forum") _ Where T.TOPIC_ID = TopicID _ Select T).First()...presuming the property is called "Replies" and not "Replys". :)
Now you can look at FT.Replies to see the reply and FT.Forum to see the Forum.
Don't use Add. That's to do an INSERT into your DB, and of course those records are already there. That's what the error means.
The key insight here is that all relationships are two-way. You can see the related object from either side of the relationship.
更多推荐
发布评论