【问题标题】:One to One relationship in Entity Framework MVCEntity Framework MVC 中的一对一关系
【发布时间】:2016-04-20 18:55:00
【问题描述】:

我想在 EF 中与 MVC 建立一对一的关系,但有点困惑

这是我的模型...

public class Event
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public Guid CategoryId { get; set; }
    public string EventTitle { get; set; }
    public string ImgUrl { get; set; }
    public string Venue { get; set; }
    public int SeatsAvailable { get; set; }
    public string Description { get; set; }
    public DateTime EventDate { get; set; }
    public DateTime EventAddedDate { get; set; }

    [Required]
    [ForeignKey("CategoryId")]
    public virtual Category Category { get; set; }

}

和

public class Category
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public string CategoryName { get; set; }
    public virtual Event Event { get; set; }
}

我想将类别 ID 存储在 Event 中,所以我像这样在 fluentApi 中创建了关系...

modelBuilder.Entity<Event>()
            .HasRequired(a => a.Category)
            .WithOptional(b => b.Event);

但更新数据库时出现此错误...

System.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'Event_Category_Source' in relationship 'Event_Category'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.

【问题讨论】:

标签: c# entity-framework model-view-controller ef-code-first ef-fluent-api


【解决方案1】:

查看答案:https://stackoverflow.com/a/18726038/4254779

modelBuilder.Entity<Event>()
        .HasKey(t => t.Id);

modelBuilder.Entity<Event>()
    .HasRequired(a => a.Category)
    .WithOptional(b => b.Event);

【讨论】:

    【解决方案2】:

    EF 不会让您在具有独立 PK 的两个实体之间创建一对一关系并同时映射 FK 属性。这是因为实体框架要求应使用依赖实体的主键也可以作为外键。

    public class Principal
    {
      [Key]
      public Guid Id{get;set;}
    
      public virtual Dependent Dependent{get;set}
    }
    
    public class Dependent
    {
      [Key,ForeignKey("Principal" )]
      public Guid PrincipalId{get;set;}
    
      public virtual Principal Principal{get;set}
    }
    

    要解决此问题,请从 Event 中删除 FK 属性,并从 Category 导航属性中删除 ForeignKey 属性。在这种情况下不需要 Fluent Api 配置。

    public class Event
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; set; }
        //public Guid CategoryId { get; set; }
    
        [Required]
        //[ForeignKey("CategoryId")]
        public virtual Category Category { get; set; }
    
    }
    

    【讨论】:

    • 那么当我创建特定类别的事件时,我将如何存储 categoryId。
    • 英孚会为您服务。如果您检查您的数据库,您将看到您仍然有一个 Fk,但如果您设置 Category 导航属性,EF 将管理该 Fk
    猜你喜欢
    • 2017-02-17
    • 2019-08-07
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2013-01-26
    相关资源
    最近更新 更多