EF Code-First创建了一些字段,甚至我添加了ForeignKey注释

时间:2013-08-18 09:01:09

标签: entity-framework data-annotations

任何人都可以帮助我吗?

这是我的2个班级

class Request
{
    public Nullable<int> BuyCurrencyId {get ; set;}
    public Nullable<int> SaleCurrencyId {get ; set;}

    [ForeignKey("SaleCurrencyId")]
    public virtual Currency SaleCurrency { get; set; }

    [ForeignKey("BuyCurrencyId")]
    public virtual Currency BuyCurrency { get; set; }
}


class Currency
{
     public int Id { get; set; }
     public string Name { get; set; }

     public virtual ICollection<Request> Requests { get; set; }
     public virtual ICollection<Request> Requests1 { get; set; }
}

我检查了更新的EF数据库,我发现EF创建了这样的Reqyests表:

SaleCurrencyId int  (Already exists)
BuyCurrencyId  int  (Already exists)
Currency_Id    int  (Added by EF)
Currency_Id1   int  (Added by EF)

这不是我所期待的。我的最后两列不正确,它们不存在。

任何人都可以帮助我吗?

我正在使用EF 6 alpha通过T4使用我生成的模型更新现有数据库。请记住我要使用数据注释,而不是 Fluent API

抱歉我的英文不好

更新1

我想如果我将Currency类更改为this它将解决我的问题,但事实并非如此。

class Currency
{
     public int Id { get; set; }
     public string Name { get; set; }

     [InverseProperty("SaleCurrencyId")]
     public virtual ICollection<Request> Requests { get; set; }
     [InverseProperty("BuyCurrencyId")]
     public virtual ICollection<Request> Requests1 { get; set; }
}

1 个答案:

答案 0 :(得分:2)

您的Update1几乎是正确的解决方案,但[InverseProperty]属性的参数必须是Request中的导航属性,而不是外键属性:

[InverseProperty("SaleCurrency")]
public virtual ICollection<Request> Requests { get; set; }

[InverseProperty("BuyCurrency")]
public virtual ICollection<Request> Requests1 { get; set; }