MVC EF code首先一对一的关系错误

编程入门 行业动态 更新时间:2024-10-24 13:21:06
本文介绍了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首先一对一的关系错误

本文发布于:2023-11-14 13:52:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   关系   MVC   EF   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!