Inserting multiple rows into a table using Entity Framework

前端 未结 3 563
[愿得一人]
[愿得一人] 2021-01-20 08:15

I’m having fun with EF and have come unstuck.

Originally I used the following bit of code using standard linq that essentially enters some data into a table.

相关标签:
3条回答
  • 2021-01-20 08:42

    Try the following code:

    
    manPref.tblManagePreference.Add(prefMemberID);
    manPref.tblManagePreference.Add(prefLocationID);
    manPref.SaveChanges();
    
    0 讨论(0)
  • 2021-01-20 08:58

    I presume you have recreated your model in the Entity Framework designer? This should have created a class deriving from ObjectContext specific to your model. By convention, this ends in "Entities".

    Have a look at your ManagePreferencesEntities instance - or whatever yours is called. It should have a property on it corresponding to the table for your entities, tblManagePreferences perhaps. This is the ObjectSet instance for that specific table, and it has an AddObject method that you can use to add entities into that table.

    Try this instead of the last 5 or so lines of code:

    manpref.tblUserPreferences.AddObject(prefMemberId);
    manpref.tblUserPreferences.AddObject(prefLocationId);
    manpref.SaveChanges();
    

    By default ObjectSet doesn't support adding lists of things, but it's easy to create your own extension method:

    public static class ObjectSetExtensions
    {
         public static void AddObjects<T>(this ObjectSet<T> objectSet, IEnumerable<T> objects)
         {
             foreach (var item in objects)
             {
                objectSet.AddObject(item);
             }
         }
    }
    
    0 讨论(0)
  • 2021-01-20 09:00

    I'm using entity framework 5 now.
    When you use:

    objectcontext.Add(yourobject1);
    objectcontext.Add(yourobject2);
    objectcontext.SaveChanges();
    

    then only last of your objects will be inserted into database.

    But if you will use:

    objectcontext.Entry(yourobject1).State = System.Data.EntityState.Added;
    objectcontext.Entry(yourobject2).State = System.Data.EntityState.Added;
    objectcontext.SaveChanges();
    

    Then all of your objects will be added.

    0 讨论(0)
提交回复
热议问题