我有三个恩赐
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Customerid { get; set; }
public string Name { get; set; }
public string email { get; set; }
public string Phoneno { get; set; }
}
和第二次Enitity
public class Merchant
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Merchantid { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string MerchantName { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string BusinessName { get; set; }
[Required]
public string OfficePhno { get; set; }
}
public class Transaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TransactionId { get; set; }
public int Merchantid {get; set;}
public int Customerid {get; set;}
public int Amount { get; set; }
public Customer customer {get; set;}
public Merchant merchant {get; set;}
}
在上面的交易表中有两个ID商家ID和客户ID我希望这是客户和商家表的外键, 请解释我如何添加外键约束我经历了很多例子,但是没能得到答案
另一个疑问是,如果我在Transaction表中添加Customer类型,我能否在Entity的事务表中获取customer的详细信息 框架
我试图通过以下代码添加Constraint
[ForeignKey("Customerid")]
pubic virtual Customer customer {get; set;}
我得到如下例外
其他信息:属性'Customer'上的ForeignKeyAttribute 类型'Dutch.Models.Transaction'无效。外键名称 在依赖类型上找不到“Customerid” 'Dutch.Models.Transaction'。 Name值应以逗号分隔 外键属性名称列表。
答案 0 :(得分:0)
我终于通过Foreignkey约束了 我的模型现在看起来像这样
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Customerid { get; set; }
public string Name { get; set; }
public string email { get; set; }
public string Phoneno { get; set; }
public ICollection<Transaction> Transactions { get; set; }
}
public class Merchant
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Merchantid { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string MerchantName { get; set; }
[Required]
[RegularExpression("^[\\p{L} .-]+$", ErrorMessage = "Use letters only please")]
public string BusinessName { get; set; }
[Required]
public string OfficePhno { get; set; }
public ICollection<Transaction> Transactions { get; set; }
}
因此,客户和商家将拥有一系列交易
并在交易表中
public class Transaction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int TransactionId { get; set; }
public int Merchantid {get; set;}
public int Customerid {get; set;}
public int Amount { get; set; }
[ForeignKey("Customerid")]
public Customer customer {get; set;}
[ForeignKey("Merchantid")]
public Merchant merchant {get; set;}
}