Entity Framework 4 Code First 是否支持像 NHibernate 这样的身份生成器? [英] Does Entity Framework 4 Code First have support for identity generators like NHibernate?
问题描述
一年前问的这个问题很相似:实体框架 4 是否支持生成器像 NHibernate 一样的 id 值?
This question, asked a year ago, is similar: Does the Entity Framework 4 support generators for id values like NHibernate?
但我想知道的是,代码优先 CTP 是否添加了对身份生成策略的支持.如果没有,有没有人知道 EF 中的一个很好的扩展点来实现类似的东西?
But what I'd like to know is if the code first CTP adds support for identity generation strategies. If not, does anyone know a good extension point in EF to implement something similar?
我目前正在使用使用 GUID 作为标识符的模型类.当使用 EF 插入时,它们会保留它们的 Guid.Empty
初始值.我知道您可以将数据库中的列的默认值设置为 newid()
但这违背了客户端身份生成的目的.
I'm currently working with model classes which use GUID as the identifier. When inserting using EF they retain their Guid.Empty
initial values. I know that you can set a default value for the column in the DB to newid()
but that defeats the purpose of client-side identity generation.
实体框架还不够成熟,无法在分布式、断开连接的系统中使用吗?
Is Entity Framework just not mature enough to be used in a distributed, disconnected system?
推荐答案
不,实体框架代码优先仍然只是 EFv4 的很好的包装器.没有像生成器那样的 NHibernate.如果您想要客户端 Id 生成器,您将必须覆盖派生 DbContext
中的 SaveChanges
并实现您自己的将 Id 分配给新实体的逻辑.
No, Entity framework code-first is still just nice wrapper around EFv4. There are no NHibernate like generators. If you want client side Id generator you will have to override SaveChanges
in derived DbContext
and implement your own logic of assigning Ids to new entities.
一些高级别的例子:
public class Context : DbContext
{
// Helper for example
// DO NOT USE IN REAL SCENARIOS!!!
private static int i = 0;
public DbSet<MyEntity> MyEntities { get; private set; }
public Context()
: base("connection")
{
MyEntities = Set<MyEntity>();
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>().HasKey(e => e.Id);
// Turn off autogeneration in database
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.HasDatabaseGeneratedOption(HasDatabaseGeneratedOption.None);
// Other mapping
}
public override int SaveChanges()
{
foreach (var entry in ChangeTracker.Entries<MyEntity>()
.Where(e => e.State == EntityState.Added))
{
// Here you have to add some logic to generate Id
// I'm using just static field
entry.Entity.Id = ++i;
}
return base.SaveChanges();
}
}
public class MyEntity
{
public int Id { get; set; }
// Other properties
}
这篇关于Entity Framework 4 Code First 是否支持像 NHibernate 这样的身份生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!