在表实体框架之间配置多个1到0..1关系 [英] Configuring multiple 1 to 0..1 relationships between tables entity framework

查看:87
本文介绍了在表实体框架之间配置多个1到0..1关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是今天的早期帖子:

Following on from earlier posts today:

没有导航属性的实体框架一对零或一个关系

首先了解实体框架代码中的ForeignKey属性

我现在正在尝试配置以下关系:

I'm now trying to configure the following relationships:

Item1具有可选的RawData
Item2具有可选的RawData
Item3具有可选的RawData

Item1 has optional RawData Item2 has optional RawData Item3 has optional RawData

RawData必须附加到Item1,Item2或Item3-不应单独存在。

RawData must be attached to either Item1, Item2 or Item3 - it would not be expected to exist on its own.

当前结构为:

class ItemX
{
    [Key]
    public int Id { get; set; }

    public int? RawDataId { get; set; }
    [ForeignKey("RawDataId")]
    public virtual RawData RawData { get; set; }
}

public class RawData
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    //other properties
}

我认为这是可以使用以下命令进行配置:

I thought this might be configured using:

modelBuilder.Entity<Item1>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);
modelBuilder.Entity<Item2>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);
modelBuilder.Entity<Item3>().HasOptional(d => d.RawData).WithOptionalPrincipal().WillCascadeOnDelete(true);

但这给出了以下错误:


类型'Item1'上属性'RawData'的ForeignKeyAttribute无效
。在相关的
类型'RawData'上找不到外键名称'RawDataId'。

The ForeignKeyAttribute on property 'RawData' on type 'Item1' is not valid. The foreign key name 'RawDataId' was not found on the dependent type 'RawData'.

这是相同的错误我今天在较早的职位上处理过。在这种情况下,我了解了由于共享主键而无法使用的原因。但是在本例中情况并非如此,因为RawData不能与Item1共享主键,因为Item2可能具有相同的ID。

This is the same error I was dealing with in an earlier post today. In that one I understand the reason it wasn't working due to a shared primary key. But that can't be the case in this example as RawData can't share a primary key with Item1 as Item2 might have the same id.

感谢您的帮助。

编辑

我已经使用:

modelBuilder.Entity<Item1>().HasOptional(d => d.RawData).WithMany().HasForeignKey(d=>d.RawDataId).WillCascadeOnDelete(true);
//etc.

数据库看起来不错。将其描述为WithMany似乎有些奇怪,但这也许是多重关系所必需的?

Database looks ok. Seems a little odd to be describing as WithMany though but perhaps this is what is required when then are multiple relationships??

推荐答案

您需要在RawDataclass中包含Item1,Item2和Item3:

You need to include Item1, Item2, and Item3 in the RawDataclass:

public class RawData
{

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public virtual Item1 i1 {get;set;}
    public virtual Item2 i2 {get;set;}
    public virtual Item3 i3 {get;set;}
    //other properties
}

这篇关于在表实体框架之间配置多个1到0..1关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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