使用外键作为一对多中唯一主键的实体框架 [英] Entity Framework using foreign key as only primary key in one to many

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

问题描述

我首先使用Entity Framework代码设计数据库.

I am using Entity Framework code first to design the database.

我有2个具有一对多关系的模型.一个"Foo"可以具有许多"FooData",如下所示-

I have 2 models with One to Many relationship. One "Foo" can have many "FooData" as follows -

public class Foo {
  [Key]
  public string serialNumber{get; set;}
  public int someNumber {get; set;}
  public string someName {get; set;}
  // Many more properties
  // Navigation Collection
  public virtual ICollection<FooData> FooDatas{get; set;}
}

public class FooData{
  [Key]
  [ForeignKey("foo")]
  public string SerialNum {get; set;}
  public DateTime SomeTime {get; set;}
  public byte[] SomeData {get; set;}
  // Navigation property
  public virtual Foo foo {get; set;}
}

当我尝试在MVC中使用"Foo"作为脚手架模型为"Foo"添加控制器时,出现了以下错误-角色中的多重性无效.因为从属角色是指键属性,从属角色"多重性的上限必须为1.

When I try to add a controller for "Foo" in MVC, using "Foo" as a scaffolding model, it gives me this error - "Multiplicity is not valid in Role. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be 1".

在这里,我会有所帮助.

I would appreciate some help here.

谢谢

推荐答案

由于您定义的方式相同,因此两者都使用了相同的键,因此它是一对一的关系.如果您想要一个真实的一对多,则需要添加/创建另一个字段并将其设置为FooData表/实体上的复合键.

Because of how you have it defined the same key is used in both so it is a 1-to-1 relationship. If you want a real one to many you will need to add/create another field and set them up as a composite key on the FooData table/entity.

public class Foo {
    [Key]
    public string serialNumber{get; set;}
    public virtual ICollection<FooData> FooDatas{get; set;}
}

public class FooData {
  [Key, Column(Order = 0),ForeignKey("foo")]
  public string SerialNum {get; set;}
  [Key,Column(Order=1)]
  public int DataId {get;set;}
  public virtual Foo foo {get; set;}
}

这篇关于使用外键作为一对多中唯一主键的实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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