简体   繁体   中英

How to perform a generic insert in entity framework?

I want to perform a generic insert in entity framework. This is what I wrote -

static public void Insert<T>(MyEntities DataContext, T obj) where T : class
        {
            try
            {
                DataContext.AddObject(DataContext,obj);
                DataContext.SaveChanges();
            }
            catch (Exception e)
            {
                throw new Exception("Problems adding object" + e);
            }
        }

But as you can see the AddObject method is not what i want...it gives exception as it expects an enitysetname I want to pass in the object and then add that object to my database. But I cannot do AddtoObjectName() as I dont know the object. Can anyone point me in the right direction here..

In EF 4 you can do:

var os = DataContext.CreateObjectSet<T>();
os.AddObject(obj);
DataContext.SaveChanges();

And please remove the stack-eating try/catch .

The problem is that the Entity Framework allows for the possibility of multiple sets that use the same type, so it must have a type name in order to work. If you know that you won't be using multiple sets with the same type, you can follow a naming convention that makes it possible to construct the name from the type.

We had the same issue, and we originally decided to name each entity set [Type]Set (eg FormSet , ActivitySet ).

With the advent of .NET 4.0, Microsoft has exposed the API they use for pluralizing entity sets in the EF tool in Visual Studio, so we're looking at maybe sticking with the default plurals, and using that tool to figure out what the default name is (eg Forms , Activities ).

using System.Data.Entity.Design.PluralizationServices;
...
internal static readonly PluralizationService PluralizationService =
        PluralizationService.CreateService(CultureInfo.CurrentCulture);
...
static public void Insert<T>(MyEntities DataContext, T obj) where T : class
{
    try
    {
        string setName = PluralizationService.Pluralize(typeof(T).Name);
        DataContext.AddObject(setName,obj);
        DataContext.SaveChanges();
    }
    catch (Exception e)
    {
        throw new Exception("Problems adding object" + e);
    }
}

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