实体框架中的主要/外键 [英] Primary /Foreign Key in Entity Framework
问题描述
我认为不使用EF ORM设计师你的意思是新的 DbContext
来自EF 4.1的API。因为如果您不是意味着 DbContext
API,您仍然必须使用EDMX(设计师)。
您可以使用数据注释( System.ComponentModel.DataAnnotations
): KeyAttribute
和 ForeignKeyAttribute
:
public class Registry
{
public virtual int Id {get;组; }
public virtual MyEntity MyEntity {get;组;
}
public class MyEntity
{
[Key,ForeignKey(Registry)]
public virtual int RegistryId {get;组; }
public virtual Registry Registry {get;组; }
}
或者您可以使用流畅的API(覆盖 OnModelCreating
(编辑:流畅的绘图被扭转和不完整)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity< MyEntity>()
.HasKey(e => e.RegistryId);
modelBuilder.Entity< MyEntity>()
.Property(e => e.RegistryId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity< MyEntity>()
.HasRequired(e => e.Registry)
.WithRequiredDependent(r => r.MyEntity);
}
其中 MyEntity
您的实体与FK和 Registry
是1:1关系中的主体。
I have created an entity class in my MVC 3 application. One of the attribute named RegistryId is primary key as well as foreign key. How can I make a column primary key as well as Foreign key ? I am not using EF ORM designer. I am coding classes by hand.
I think by "not using EF ORM designer" you mean new DbContext
API from EF 4.1. Because if you don't mean DbContext
API you still have to use EDMX (designer).
You can either use data annotations (System.ComponentModel.DataAnnotations
): KeyAttribute
and ForeignKeyAttribute
:
public class Registry
{
public virtual int Id { get; set; }
public virtual MyEntity MyEntity { get; set; }
}
public class MyEntity
{
[Key, ForeignKey("Registry")]
public virtual int RegistryId { get; set; }
public virtual Registry Registry { get; set; }
}
Or you can use fluent API (overriding OnModelCreating
in your derived context):
(Edit: fluent mapping was reversed and incomplete)
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyEntity>()
.HasKey(e => e.RegistryId);
modelBuilder.Entity<MyEntity>()
.Property(e => e.RegistryId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
modelBuilder.Entity<MyEntity>()
.HasRequired(e => e.Registry)
.WithRequiredDependent(r => r.MyEntity);
}
Where MyEntity
is your entity with FK and Registry
is principal entity in 1:1 relationship.
这篇关于实体框架中的主要/外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!