且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Entity Framework将多个行插入表中

更新时间:2022-04-02 08:35:45

我想您已经重新创建你的模型中的实体框架设计师?这应该已经创建了ObjectContext中从一个特定类派生到模型。按照约定,该结束的实体

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

有一个在你的 ManagePreferencesEntities 实例 - 无论你是调用。它应该具有在对应于表的实体它, tblManagePreferences 也许一个属性。这是针对特定的表对象集实例,它有您可以使用实体添加到 ADDOBJECT 方法。该表

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.

尝试,而不是过去的5行左右的代码如下:

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);
         }
     }
}