Reputation: 770
I just wan't to know if it's possible to assign a customized primary key only when the ObjectContext.SaveChanges() is called?
I'm trying to search for any solutions but it seems like I'am the only one thinking about this.
It is the same as what is happening when you have an identity column which the EF will automatically assign a primary key once the ObjectContext.SaveChanges() is called but instead of the primary key being an auto identity column, I want to customize my own primary key.
Thanks in advance guys.
Edit: Additional Details
example I have this class:
public class Transaction()
{
public string ID { get; set; }
public DateTime TransactionDate { get; set; }
}
I wan't to add the class in the objectset like this:
Transaction trans = new Transaction()
{
ID = null,
TransactionDate = DateTime.Now
};
ObjectSet.AddObject(trans);
Notice that I haven't assign the ID yet, I want it to be assigned only when the user click save which will call the
ObjectContext.SaveChanges();
One the user call this, I will get a new primary key and assign it to the trans instance.
Upvotes: 1
Views: 304
Reputation: 3118
Not ideal but consider changing your model to this. Your POCO now contains some logic which is not good but it allows you to customize the save to create your id from the third party class library. The string ID column will resolve to a primary key of type nvarchar(128) by default. Your ID will be null prior to the save.
public abstract class Entity
{
public virtual void OnSave();
}
public class Transaction : Entity
{
public string ID { get; set; }
public DateTime TransactionDate { get; set; }
public override void OnSave()
{
ID = Guid.NewGuid().ToString(); //call to class library
}
}
You can hook into the SaveChanges method by overriding it in your DbContext
public class MyContext : DbContext
{
public DbSet<Transaction> Trans { get; set; }
public MyContext () : base()
{
}
public override int SaveChanges()
{
var changedEntities = ChangeTracker.Entries();
foreach (var changedEntity in changedEntities)
{
var entity = (Entity)changedEntity.Entity;
entity.OnSave();
}
return base.SaveChanges();
}
}
Upvotes: 1