实体框架MVC中的一对一关系



我想用MVC在EF中创建一对一关系,但有点混淆

这是我的模型。。。

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

我想在Event中存储类别Id,所以我在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 '*'.

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

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

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

相关内容

  • 没有找到相关文章

最新更新