开发者

How to save EntityObject

Lets say i have a lot of entity classes. I have a db context.

I have a code

Person p=new Person();
p.Name="test";

Note, that there is no lines with context.

How must I save this object using context, if context only knows that it is EntityObject?

UPDATE:

if (obj.EntityState == System.Data.EntityState.Detached)
                context.AddObject(obj.EntityKey.EntitySetName, obj);

but obj.EntityKey is null, so it does not work

UPDATE2:

I have a code:

public static void EntitySave(EntityObject obj)
        {
            if (obj == null)
                throw new ArgumentNullException(obj.GetType().Name, obj.GetType().Name + " не должен быть пустым");
            var context = GetSqlConnection();

            if (obj.EntityState == System.Data.EntityState.Detached)
                context.AddObject(obj.EntityKey.EntitySetName, obj);//there is an exception

            context.SaveChanges();
        }

and one another:

 public static void SaveNewPerson()
        {
            Person p = new Person();
            EntitySave(p);//there is开发者_如何学JAVA an exception
        }

So how EntitySave should save the object correctly? Or may be i need a helper functions to create each entities classes?


You cannot do it by passing EntityObject alone, because a newly created EntityObject has no info on the entity set. You can create a helper function or a helper dictionary, something like

private static Dictionary<Type, string> _entitySets = new Dictionary<Type, string>
{
    { typeof(Person), "Persons"},         
    { typeof(Address), "Addresses"}
}

...

public static void EntitySave(EntityObject obj)
{
    if (obj == null)
        throw new ArgumentNullException("не должен быть пустым");

    var context = GetSqlConnection();
    if (obj.EntityState == System.Data.EntityState.Detached)
        context.AddObject(EntitySets[obj.GetType()], obj);

    context.SaveChanges();
}

Just check if the set name is "Persons" or "PersonsSet"


It is still not clear what you mean by "context doesn't know the type of object". The context must know the type of object otherwise it doesn't know how to map and persist the object. The type of the object is described in EDMX.

If you just want to add object to the context you must use either:

// You must say the name of EntitySet where you want to add the object
context.AddObject("PersonsSet", person);

or:

// You must call the AddObject method on correct object set
context.CreateObjectSet<Person>().AddObject(person);

Default code generation also offers specific method like AddPerson or something like that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜