.NET EF4中的实体的通用创建

时间:2011-10-13 08:50:00

标签: .net entity-framework-4

我在创建实体对象时遇到问题。我不知道对象类型,但我有要创建的实体的名称和主键的名称。此功能显示问题:

        /// <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;
    }

1 个答案:

答案 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;
}