MVC EF code首先一对一的关系错误 [英] MVC EF Code First one to one relationship error

查看:126
本文介绍了MVC EF code首先一对一的关系错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有看台的列表(在贸易展)和参展商的名单。

I want to have a list of stands (at a trade show) and a list of exhibitors.

看台上的列表是分开的参展商名单 - 但是,一旦注册,我要参展商能够预定展位

The list of stands is separate to the list of exhibitors - however, once registered, I want the exhibitor to be able to book a stand.

当他们选择/本书立场 - 我希望再能有一个列表看台在我看来,也显示出相关的参展商谁已预订其

When they select/book a stand - I would like to then be able to have a list the stands in my view, and also show the associated exhibitor who has booked it.

同样,我想列出另一种观点认为,参展商,还立着,他们已预订。

Likewise, I would like to list in another view, the exhibitors, and also which stand they have booked.

所以我想安装一个一对一的关系(使用EF codeFirst)。

So I'm trying to setup a one to one relationship (using EF CodeFirst).

不过,尝试添加一个控制器,无论是展位还是参展商的时候,我收到以下错误:

However, when trying to add a controller for either the Stand or the Exhibitor, I get the following error:

我的型号是:

 public class Stand
{
    public int StandID { get; set; }
    public string Description { get; set; }
    public bool Booked { get; set; }
    public int ExhibitorID { get; set; }
    public virtual Exhibitor Exhibitor { get; set; }

}

 public class Exhibitor
{
    public int ExhibitorID { get; set; }
    public string Company { get; set; }
    public int StandID { get; set; }
    public virtual Stand Stand { get; set; }

}

我敢肯定这件事情做模型的虚拟的一部分。

I'm certain it's something to do with the "Virtual" part of the models.

任何人都可以请帮指出什么应该被更新,以允许连接?

Can anyone please help point out what should be updated, to allow the connection?

感谢您,

标记

推荐答案

EF不知道哪一个实体是主要的(父),哪一个是相关的(孩子)。需要声明在该实体应该首先该项目的外键。你可以用注释或流利的映射做到这一点。

EF doesn't know which entity is the principal (parent) and which is the dependent (child). You need to declare a foreign key on the item that entity that should come first. You can do this with an annotation or a fluent mapping.

注释

添加以下命名空间:

using System.ComponentModel.DataAnnotations.Schema;

注释你的通过以下标注类:

public class Stand
{
    [ForeignKey("Exhibitor")]
    public int StandID { get; set; }
    public string Description { get; set; }
    public bool Booked { get; set; }
    public int ExhibitorID { get; set; }
    public virtual Exhibitor Exhibitor { get; set; }

}

流利的映射

覆盖你的 OnModelCreating 方法在的DbContext 类,包括:

Override your OnModelCreating method in your DbContext class to include:

modelBuilder.Entity<Stand>()
    .HasOptional(s => s.Exhibitor)
    .WithRequired(e => e.Stand);

这篇关于MVC EF code首先一对一的关系错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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