开发者

Entity Framework throwing InvalidOperationException when trying to load child tables

I am using Entity Framework with asp .net mvc. I have a repository class that initializes an instance of the entities in the constructor. Let's say I have the familiar customers table that has 1 to many rows in an orders table: Customer has many orders.

I have tried the following 2 ways to load the orders associated with customer, but without success.

Attempt 1: Use Include

Result: Throws InvalidOperationException "The Value property has already been set on this EntityReference.开发者_StackOverflow社区 More than one related object cannot be added to an EntityReference".

public List<Customer> GetCustomerList()
{
  return _database.CustomerSet.Include("Orders").ToList();
}

Attempt 2: Use Load

Result: Same exception, thrown on cust.Orders.Load()

public List<Customer> GetCustomerList()
{
  List<Customer> customers = _database.CustomerSet.ToList();
  foreach(Customer cust in customers)
  {
     if(!cust.Orders.IsLoaded)
     {
        cust.Orders.Load();
     }
  }
}

Is anyone familiar with this exception? Any suggestions on what might be the cause of this?

After using profiler, I know that it executes this query successfully to get all customers:

SELECT 1 AS [C1], [Extent1].[Name] AS [Name] .... 
FROM [dbo].[Customer] AS [Extent1]

Executes this query to get orders associated with the first customer (id=31):

SELECT 1 AS [C1], [Extent1].[ID] AS [ID] ... 
FROM [dbo].[Orders] AS [Extent1] 
WHERE [Extent1].[Customer_ID] = 31

It blows up after this, when it's associating the data pulled back from this query to the Customer model.


Looks like your assotiation is wrong and EF thinks that Customer can have only 1 order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜