2017-06-20 109 views
1

所以我想如下创建一个简单的产品 - 预览1对1的关系:EF代码首先不是一个外键设置为一个关系

public class Product : BaseEntity 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    public Guid Id { get; set; } 
    public string name { get; set; } 
    public virtual EPS eps { get; set; } 
    public virtual Preview preview { get; set; } 

    [ForeignKey("userId")] 
    public virtual User user { get; set; } 
    public Guid userId { get; set; } 

} 

public class Preview : BaseEntity 
{ 
    [Key,ForeignKey("Product")]   
    public Guid Id { get; set; } 
    public string imagePath { get; set; } 
    public double width { get; set; } 
    public double height { get; set; } 
    public virtual List<TextPreview> Texts { get; set; } 
    public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; } 
    [ForeignKey("ProductId")] 
    public virtual Product Product { get; set; } 
    public virtual Guid ProductId { get; set; } 
} 

我期待在预览表中有一个外键,它将指向一个产品 ,但在运行迁移后,我将它作为常规字段

enter image description here

我做错了什么?

回答

0

你几乎有它,你只是错过了一个一块拼图......

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

您还需要添加...

public Guid ProductId { get; set; } 

到预览对象。

还值得注意的是,ForeignKey attrib可以放在任何一个属性上,而字符串必须指向另一个。

由于它正在写入,因此您正试图使Id属性为相关表上的主键和外键指定值。

因此,最终的代码可能看起来像......

public class Product : BaseEntity 
{ 
    [Key] 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]   
    public Guid Id { get; set; } 
    [ForeignKey("User")] 
    public Guid UserId { get; set; } 
    public string name { get; set; } 

    public virtual EPS eps { get; set; } 
    public virtual Preview preview { get; set; } 
    public virtual User user { get; set; } 
} 

public class Preview : BaseEntity 
{ 
    [Key]   
    public Guid Id { get; set; } 

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

    public string imagePath { get; set; } 
    public double width { get; set; } 
    public double height { get; set; } 

    public virtual List<TextPreview> Texts { get; set; } 
    public virtual List<ImagePlaceHolder> ImagePlaceHolders { get; set; } 

    public virtual Product Product { get; set; } 
} 

作为一个方面说明我还建议不要使用像List<T>具体集合类型,而不是使用像IList<T>ICollection<T>它促进更好的代码重用和可扩展性。

+0

感谢您的帮助,但是如果我遵循您的建议,最终会出现此错误:多重性在“Preview_product”关系中的'Preview_product_Source'角色中无效。因为“依赖角色”属性不是关键属性,所以“依赖角色”的多重性的上界必须为“*”。 –

+0

这就是这个问题解决,你现在有一个不同的问题,这里解释这里... https://stackoverflow.com/questions/9292738/entity-framework-4-0-error-113-multiplicity-is-not-valid在角色 – War

+0

基本上你有1对1的关系,它似乎可能是问题,你想要的是一个0-1到1的关系...使guid ProductId可为空“Guid?”可以解决这个问题 – War