实体框架中的主要/外键 [英] Primary /Foreign Key in Entity Framework

查看:108
本文介绍了实体框架中的主要/外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的MVC 3应用程序中创建了一个实体类。名为RegistryId的属性之一是主键以及外键。如何使列主键和外键?我没有使用EF ORM设计师。我正在手工编写课程。

解决方案

我认为不使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆