简体   繁体   中英

Entity Framework lazy loading fails for properties of just added entity

Trying to get a property via lazy loading of a just added entity fails.

The only solution I've found until now is to decomment the commented code ,in other words to create another Manager which in turn creates another Context since each Manager has an instance of the Context and then re-query the entity.

I also tried creating a shared Context instance between all Managers but same result. Any idea why recreating the Context solves it and how to fix this?

Here is the code I use to test:

    IOrderManager ordManager = new OrderManager();

    [TestMethod]
    public void CategoryFromOrder()
    {
        Order order = new OrderBuilder()
            .SetCategory(2)
            .SetLegalForm(8)
            .SetClientIdentifier(new Random().Next(11111111,99999999).ToString())
            .SetLastName("Chaouachi")
            .SetFirstName("Saif")
            .SetQuantity(450)
            .SetStatus(Order.StatusValues.New)
            .SetAccountHolder("John")
            .SetPrimaryKey(PrimaryKeyFactory.GetOrderPrimaryKey(null, 1, 2))
            .Build();


        int res = ordManager.AddOrder(order);


    //ordManager = new OrderManager();                       
    // order = ordManager.GetOrder(PrimaryKeyFactory.GetOrderPrimaryKey(res, 1, 2));

        var categ = order.Category;

        Assert.IsNotNull(categ);
    }

For lazy loading to work with Code First Entity Framework you need a proxy object (an instance of a class inherited from your original POCO class). It is not obvious from your code but I expect that the original object is created via new Order() and if you want a proxy object you should use DataContext.Orders.Create(). The resulting object will be a proxy and lazy loading will work.

http://msdn.microsoft.com/en-us/library/gg679504(v=vs.113).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM