EF迁移由于GUID外键而失败

时间:2018-12-07 00:12:17

标签: c# entity-framework asp.net-core

我的.NET Core 2.1应用程序中具有以下模型:

public class Product
{
    [Key]
    public Guid ProductId { get; set; }

    public virtual ICollection<Favourite> Favourites { get; set; }

}

public class Retailer
{
    [Key]
    public Guid BusinessId {get; set;}

    public virtual ICollection<Favourite> Favourites { get; set; }
}

public class Favourite
{

    [Key]
    public Guid FavouriteId { get; set; }

    [ForeignKey("Retailer_BusinessId")]
    public virtual Retailer Business { get; set; }

    [ForeignKey("Product_ProductId")]
    public virtual Product Product { get; set; }

}

当尝试运行EF迁移时,出现以下错误:

  

从“收藏夹。业务”到“零售商。收藏夹”的关系   具有外键属性{'Retailer_BusinessId':Nullable}   无法定位主键{'BusinessId':Guid},因为它不是   兼容。配置主键或一组兼容的外键   关系的关键属性。

我怀疑是因为我在外部表中使用Guid作为键。我该如何告诉EF

1 个答案:

答案 0 :(得分:2)

似乎EF期望ForeignKey属性引用导航属性。我能够重现您收到的错误,并进行了以下更改后,它已成功迁移。

public class Favourite
{
    [Key]
    public Guid FavouriteId { get; set; }

    [ForeignKey("Business")]
    public Guid BusinessId { get; set; }

    [ForeignKey("Product")]
    public Guid ProductId { get; set; }

    public virtual Retailer Business { get; set; }

    public virtual Product Product { get; set; }
}

编辑:您的操作已接近完成,但是您需要拥有该属性,然后在ForeignKey属性中仅指定该属性的名称。

public class Favourite
{
    [Key]
    public Guid FavouriteId { get; set; }

    public Guid BusinessId { get; set; }

    public Guid ProductId { get; set; }

    [ForeignKey("BusinessId")]
    public virtual Retailer Business { get; set; }

    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
}