views:

44

answers:

1

Hi All,

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,
  • Reply

so 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).First

but 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 FT

But 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.

+2  A: 
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.

Craig Stuntz