coyote76
coyote76

Reputation: 13

generic creation of entities in .NET EF4

i have a problem in creating an entity object. i dont know the object type, but i have the name of the entity to create and the name of its primary key. this function shows the problem:

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

Upvotes: 1

Views: 424

Answers (1)

Eranga
Eranga

Reputation: 32447

You can use reflections to make the call to CreateObject method as described here.

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

Upvotes: 1

Related Questions