1

We are about to move our old application which had its own persistence objectMngr to the new Entity framework, this works fine. The Problem is that the old ObjectMngr used to sae Primary keys as strings annd sometimes in its own format, now in order to implement a compatible persistence leyer i need to Configure the EF to use the same format or eventuelly to modify the Entities PK's bevor saving.

I'm assuming this is possible, does anybody know where can i do that?

Thnx

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130

2 Answers2

1

You need to set StoreGeneratedPattern for your primary key properties to None. After that you can assign primary key value yourselves by using the same code you have been using in your old solution.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

This question was asked several times at Stackoverflow. Please read this response: Does Entity Framework 4 Code First have support for identity generators like NHibernate?

It solves the problem described by you. If you do not use the code first approach as in your case, then overwrite the SaveChanges method in the generated class that inherits from ObjectContext. The class DbContext is only used for Code First approach. E.g.:

public interface IEntity
{
    string Id { get; set; }
}

public partial class MyEntity: IEntity
{
}

public partial class MyEntities
{
    public override int SaveChanges(System.Data.Objects.SaveOptions options)
    {
        var generator = new IdGenerator();

        foreach(var entry in this.ObjectStateManager.GetObjectStateEntries(EntityState.Added))
        {
            var entity = entry.Entity as IEntity;
            if (entity != null)
            {
                entity.Id = generator.CreateNewId();
            }
        }

        return base.SaveChanges(options);
    }
}

This example assumes, that you implement IEntity for all classes in your model (like MyEntity), which depends on a special generation for the PK and MyEntities is an ObjectContext. IdGenerator should offer your method of providing the primary key. This code also requires, that the property Id is located in the generated code.

Community
  • 1
  • 1
54v054r3n
  • 394
  • 2
  • 10