4

我想要一份展位清单(在贸易展上)和参展商清单。

展位列表与参展商列表是分开的 - 但是,一旦注册,我希望参展商能够预订展位。

当他们选择/预订展位时 - 我希望能够在我的视图中列出展位,并显示已预订的相关参展商。

同样,我想在另一个视图中列出参展商,以及他们预订的展位。

所以我正在尝试建立一对一的关系(使用 EF CodeFirst)。

但是,当尝试为展台或参展商添加控制器时,我收到以下错误:

在此处输入图像描述

我的模型是:

 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; }

}

我确定这与模型的“虚拟”部分有关。

谁能帮助指出应该更新什么以允许连接?

谢谢,

标记

4

2 回答 2

5

EF 不知道哪个实体是主体(父),哪个是从属(子)。您需要在应该首先出现的实体上声明一个外键。您可以使用注释或流畅的映射来做到这一点。

注解

添加以下命名空间:

using System.ComponentModel.DataAnnotations.Schema;

Stand使用以下注释注释您的类:

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以包括:

modelBuilder.Entity<Stand>()
    .HasOptional(s => s.Exhibitor)
    .WithRequired(e => e.Stand);
于 2012-08-25T14:21:06.190 回答
3

您创建的模型无法与关系数据库一起使用。Stand需要一段时间ExibitorId需要Exibitor一个。StandId循环关系不允许您向任一表插入任何行。

假设一个Exibitor可能有多个Stand并将关系转换为一对多是一种选择。

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 virtual ICollection<Stand> Stands { get; set; }
}

或者您可以使用共享主键映射来建立一对一的关系。Stand主要实体在哪里。将Exibitor使用StandID作为它的PK。

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

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

使用 Fluent API 配置关系。

modelBuilder.Entity<Exibitor>().HasRequired(e => e.Stand)
    .WithOptional(s => s.Exibitor);
于 2012-08-25T14:16:45.713 回答