我想使用 EF4 将实体映射到具有顺序 guid 作为 PK 的表。根据这篇文章http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/ EF4 支持这一点,但带有 edmx 映射。有没有办法在使用 EF4 Code First 时使用服务器生成的 Guid,如果是,如何使用?
问问题
6769 次
1 回答
12
是的,您必须映射您的 Key 属性。假设您有一个实体,例如:
public class MyEntity
{
public virtual Guid Key { get; set; }
...
}
然后你可以定义DbContext
派生类,如:
public class Context : DbContext
{
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.Key);
modelBuilder.Entity<MyEntity>()
.Property(e => e.Key)
.HasDatabaseGeneratedOption(DatabaseGenerationOption.Identity);
// Other mapping
}
}
或者您可以简单地使用数据注释定义您的实体:
public class MyEntity
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Key { get; set; }
...
}
编辑:
This works if the mapping is used with existing database but if you want EF code-first to create database for you it will use normal (not sequential) guids! Check this question for possible solutions in case of database generation.
于 2011-03-17T13:21:13.827 回答