How to perform a general insert in an entity infrastructure?

I want to perform a general insert in an entity infrastructure. 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 since you can see that the AddObject method is not what I want ... it gives an exception, because it expects the name enityset, which I want to pass in the object, and then add this object to my database. But I can not do AddtoObjectName () since I do not know the object. Can anyone point me in the right direction here.

+3
source share
2 answers

In EF 4 you can:

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

And please remove the stack try/catch.

+6
source

, Entity Framework , , . , , , .

, [Type]Set (, FormSet, ActivitySet).

.NET 4.0 Microsoft API, EF Visual Studio, , , (, 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);
    }
}
+2

Source: https://habr.com/ru/post/1751284/


All Articles