locked
Adding a newly created entity with relationships to the context RRS feed

  • Question

  • I have a table (Table3) that stores the foreign keys of two other related tables (Table1) and (Table2). Table2 stores the foreign key of Table1. I have the Table1 and Table2 entities in the code. When I create a Table3 entity, I am adding it to the context like this.

    Table3 t3 = new Table3();
    t3.Table2 = t2; // Already retrieved from the DB and in context
    t3.Table1 = t1; // Already retrieved from the DB and in context

    ObjectContext.InsertTable3(t3);

    But when I add it like this, if I query the Table3 entities based on it's relationship with Table1 and Table2 without SaveChanges(), I don't find it in the collection. When I call SaveChanges(), it sets the foreign keys appropriately. Am I doing anything wrong?

    Though it's not persisted to the store, I should be able to query them locally right? I am doing multiple inserts and I need to check if it already exists. But the query doesn't return the t3 entity I added locally.

    Any help is appreciated.
    Thursday, December 10, 2009 7:25 PM

Answers

  • Hello Basani,

     

    Welcome to ADO.NET Entity Framework and LINQ to Entities forum!

     

    For newly-added entities, the ObjectContext has not generate the Entity Key for them.  We cannot retrieve any entities without Entity Keys via the ObjectContext queries.   For detailed information about the Entity Key and Added entities, please see http://msdn.microsoft.com/en-us/library/dd283139.aspx.

     

    If you don’t want to retrieve the Added entities through their relational entities, here is one workaround to use the ObjectStateManager. 

    ==============================================================================================
                    ParentTable parent = (from p in context.ParentTable

                                          where p.id == 1

                                          select p).FirstOrDefault();

     

                    ChildTable child = new ChildTable

                    {

                        id = 2,

                        Name = "New Child"

                    };

     

                    parent.ChildTable.Add(child);

     

                    var addedChildEntry = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).

                        Where(o => !o.IsRelationship && o.Entity is ChildTable && ((ChildTable)o.Entity).id == 2).FirstOrDefault();

     

                    if (addedChildEntry != null)

                    {

                        // Get the entity

                        var addedChild = addedChildEntry.Entity as ChildTable;

                    }
    ==============================================================================================

     

    If you have any questions, please feel free to let me know.

     

    Have a great day!

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, December 11, 2009 2:45 AM

All replies

  • If I was not clear in the above post, let me gice you a code snippet:

    A Company can have many divisions. (One-to-Many)

    Entities context = new Database().Context;

     

    Company c = (from com in context.Company
                                                  .Where(o => o.CompanyID == 1)
                       select com).FirstOrDefault();

     

    Division div = new Division();
    div.DivisionName =
    "TEST";
    div.CreatedBy =
    "basanip";
    div.CreatedDate =
    DateTime.Now;
    div.ModifiedBy =
    "basanip";
    div.ModifiedDate =
    DateTime.Now;

    c.Division.Add(div);

     

    // I don't want to call the SaveChanges() yet as I have some more logic to determine adding the divisions and I need to
    // avoid duplicate divisions
    //context.SaveChanges();

     

     

    List<Division> divList = (from d in context.Division
                                                           .Where(o => o.DivisionName ==
    "TEST")
                                     select d).ToList();

    The problem is divList.Count = 0 though I expect 1 as I just added it. But when I do the following, I get what I want:

    List<Division> divList = (from d in c.Division
                                                   .Where(o => o.DivisionName ==
    "TEST")
                                     select d).ToList();

    Is there a way to access the Divisions I added to the context locally?

    Any help is appreciated!

    Thanks



    Friday, December 11, 2009 12:06 AM
  • Hello Basani,

     

    Welcome to ADO.NET Entity Framework and LINQ to Entities forum!

     

    For newly-added entities, the ObjectContext has not generate the Entity Key for them.  We cannot retrieve any entities without Entity Keys via the ObjectContext queries.   For detailed information about the Entity Key and Added entities, please see http://msdn.microsoft.com/en-us/library/dd283139.aspx.

     

    If you don’t want to retrieve the Added entities through their relational entities, here is one workaround to use the ObjectStateManager. 

    ==============================================================================================
                    ParentTable parent = (from p in context.ParentTable

                                          where p.id == 1

                                          select p).FirstOrDefault();

     

                    ChildTable child = new ChildTable

                    {

                        id = 2,

                        Name = "New Child"

                    };

     

                    parent.ChildTable.Add(child);

     

                    var addedChildEntry = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added).

                        Where(o => !o.IsRelationship && o.Entity is ChildTable && ((ChildTable)o.Entity).id == 2).FirstOrDefault();

     

                    if (addedChildEntry != null)

                    {

                        // Get the entity

                        var addedChild = addedChildEntry.Entity as ChildTable;

                    }
    ==============================================================================================

     

    If you have any questions, please feel free to let me know.

     

    Have a great day!

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, December 11, 2009 2:45 AM
  • Hello Basani,


    How is the problem?  If you need any further assistance, please feel free to let me know. 

     

    Have a great day!

     

    Best Regards,
    Lingzhi Sun

    MSDN Subscriber Support in Forum

    If you have any feedback on our support, please contact msdnmg@microsoft.com


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Tuesday, December 15, 2009 12:45 AM