简体   繁体   English

在实体框架中使用现有外键值

[英]Using existing foreign key value in entity framework

I am using Entity Framework Code First. 我正在使用Entity Framework Code First。 I have two model classes, Currency and Invoice: 我有两个模型类,货币和发票:

public class Currency
{
    [HiddenInput(DisplayValue = false)]
    public int CurrencyID { get; set; }
    public string ShortName { get; set; }
    public string FullName { get; set; }

    [Required(ErrorMessage = "Please enter a positive price")]
    public double Rate { get; set; }
}

public class Invoice
{
    public int InvoiceID { get; set; }
    public int CurrencyID { get; set; }
    public double RateOfExchange { get; set; }
    public double CurrencyAmount { get; set; }

    public virtual Currency Currency { get; set; }
    public virtual Customer Customer { get; set; }
}

I have some initialized my database with some Currency values. 我已经用一些Currency值初始化了我的数据库。 Whenever I add a new Invoice, I want it to use existing values from the Currency table for its Currency property but every time I create a new Invoice value and assign its Currency property with an existing value from the Currency table, it creates a duplicate value in the currency table. 每当我添加新的发票时,我都希望它使用“货币”表中的“货币”属性的现有值,但是每次我创建新的“发票”值并将其“货币”属性分配给“货币”表中的现有值时,它都会创建一个重复的值在货币表中。 How can I solve this problem. 我怎么解决这个问题。

Above the line: 水准之上:

public virtual Currency Currency { get; set;}

Add the following attribute: 添加以下属性:

[ForeignKey("CurrencyID")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM