是否实体框架4 code首先对身份发电机像NHibernate的支持呢? [英] Does Entity Framework 4 Code First have support for identity generators like NHibernate?
问题描述
这个问题,问一年前,是相似的:
<一href=\"http://stackoverflow.com/questions/2408994/does-the-entity-framework-4-support-generators-for-id-values-like-nhibernate\">Does像NHibernate的ID值的实体框架4支持发电机?
This question, asked a year ago, is similar: Does the Entity Framework 4 support generators for id values like NHibernate?
但我想知道的是,如果code首先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
初始值。我知道,你可以在DB列的默认值设置为 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?
推荐答案
没有,实体框架code-第一仍然是围绕EFv4刚刚好包装。还有像发电机没有NHibernate的。如果你想客户端ID生成器,你将不得不重写的SaveChanges
的衍生的DbContext
和实现自己的指定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
}
这篇关于是否实体框架4 code首先对身份发电机像NHibernate的支持呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!