如何保存EntityObject
可以说我有很多实体类。 我有一个数据库上下文。
我有一个代码
Person p=new Person();
p.Name="test";
注意,没有带有上下文的行。
如果上下文只知道它是 EntityObject,我必须如何使用上下文保存该对象?
更新:
if (obj.EntityState == System.Data.EntityState.Detached)
context.AddObject(obj.EntityKey.EntitySetName, obj);
但是 obj.EntityKey 为 null,所以它不起作用
更新 2:
我有一个代码:
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();
}
另一个:
public static void SaveNewPerson()
{
Person p = new Person();
EntitySave(p);//there is an exception
}
那么 EntitySave
应该如何正确保存对象?或者我可能需要一个辅助函数来创建每个实体类?
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 an exception
}
So how EntitySave
should save the object correctly? Or may be i need a helper functions to create each entities classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无法通过单独传递 EntityObject 来完成此操作,因为新创建的 EntityObject 没有有关实体集的信息。您可以创建一个辅助函数或辅助字典,例如
只需检查集合名称是否为“Persons”或“PersonsSet”
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
Just check if the set name is "Persons" or "PersonsSet"
目前还不清楚“上下文不知道对象的类型”是什么意思。上下文必须知道对象的类型,否则它不知道如何映射和持久化对象。对象的类型在 EDMX 中描述。
如果您只想将对象添加到上下文中,则必须使用:
或:
默认代码生成还提供特定方法,例如
AddPerson
或类似的方法。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:
or:
Default code generation also offers specific method like
AddPerson
or something like that.