我在创建实体对象时遇到问题。我不知道对象类型,但我有要创建的实体的名称和主键的名称。此功能显示问题:
/// <summary>
/// create a new entity and save it o object context
/// </summary>
/// <param name="oc"></param>
/// <param name="entityName">type name of new entity</param>
/// <param name="pkName">primary key name of new entity</param>
/// <returns></returns>
Guid genericCreate(ObjectContext oc, String entityName, String pkName)
{
// create a new primary key
Guid newPk = Guid.NewGuid();
// create new entity key
EntityKey entityKey = new EntityKey(oc.GetType().Name + "." + entityName, pkName, newPk);
// get type name of new entity
String typeName = oc.GetType().Namespace + "." + entityKey.EntitySetName;
// create a new entity
// this dont work :/
// Error: Operator '<' cannot be applied to operands of type 'method group' and 'System.Type'
var entity = oc.CreateObject<System.Type.GetType(typeName)>();
// this works, but we run in problems at another place
// var anotherEntity = Activator.CreateInstance(System.Type.GetType(typeName));
// assign entity key
IEntityWithKey entityWithKey = (IEntityWithKey)entity;
entityWithKey.EntityKey = entityKey;
// add entity to object context
String entitySetName = getEntitySetName(entityName);
oc.AddObject(entitySetName, entityWithKey);
// write to database
oc.SaveChanges();
return newPk;
}
答案 0 :(得分:1)
您可以使用反射按照here所述调用CreateObject
方法。
Guid genericCreate(ObjectContext oc, String entityName, String pkName)
{
// create a new primary key
Guid newPk = Guid.NewGuid();
// create new entity key
EntityKey entityKey = new EntityKey(oc.GetType().Name + "." + entityName, pkName, newPk);
// get type name of new entity
String typeName = oc.GetType().Namespace + "." + entityKey.EntitySetName;
// create a new entity
var method = oc.GetType().GetMethod("CreateObject");
method = method.MakeGenericMethod(System.Type.GetType(typeName));
var entity = method.Invoke(service, null);
// assign entity key
IEntityWithKey entityWithKey = (IEntityWithKey)entity;
entityWithKey.EntityKey = entityKey;
// add entity to object context
String entitySetName = getEntitySetName(entityName);
oc.AddObject(entitySetName, entityWithKey);
// write to database
oc.SaveChanges();
return newPk;
}