简体   繁体   English

如何在数据库第一个EF中定义两个不与数据注释组合的外键?

[英]How to define two foreign keys that are not composite with Data Annotations in database first EF?

In SQL, I have a table with two columns that both map to the same primary key in another table. 在SQL中,我有一个包含两列的表,这两列都映射到另一个表中的同一主键。 The easiest way to explain is using the table constraints: 解释的最简单方法是使用表约束:

ALTER TABLE [dbo].[sls_n_Promotion]  WITH CHECK ADD  CONSTRAINT [FK_SlsPromotion_SlsPromotionTradeSpendType] FOREIGN KEY([TradeSpendID])
REFERENCES [dbo].[sls_a_PromotionTradeSpendType] ([ID])
GO

ALTER TABLE [dbo].[sls_n_Promotion] CHECK CONSTRAINT [FK_SlsPromotion_SlsPromotionTradeSpendType]
GO

ALTER TABLE [dbo].[sls_n_Promotion]  WITH CHECK ADD  CONSTRAINT [FK_SlsPromotion_SlsPromotionTradeSpendType2] FOREIGN KEY([TradeSpendSubID])
REFERENCES [dbo].[sls_a_PromotionTradeSpendType] ([ID])
GO

ALTER TABLE [dbo].[sls_n_Promotion] CHECK CONSTRAINT [FK_SlsPromotion_SlsPromotionTradeSpendType2]
GO

I'm using database first, and I have created Promotion.partial.cs . 我首先使用数据库,并且创建了Promotion.partial.cs In this partial class, I'm struggling to get the Data Attributes set correctly for 'TradeSpendID' and 'TradeSpendSubID'. 在这个局部类中,我正在努力为“ TradeSpendID”和“ TradeSpendSubID”正确设置数据属性。 This is what I currently have: 这是我目前拥有的:

[Display(Name="Trade Spend Type")]
[Column("TradeSpendID")]
[ForeignKey("PromotionTradeSpendType")]
int? TradeSpendId { get; set; }

[Display(Name = "Trade Spend Sub Type")]
[Column("TradeSpendSubID")]
[ForeignKey("PromotionTradeSpendType")]
int? TradeSpendSubId { get; set; }

When I go to create a Controller using scaffolding, I get the error: 当我使用脚手架创建控制器时,出现错误:

Unable to determine a composite foreign key ordering for foreign key on type... 无法确定类型上的外键的复合外键顺序...

This isn't a composite foreign key. 这不是复合外键。

Question: How do I use Data Attributes for the foreign keys on those 2 properties? 问题: 如何对这两个属性的外键使用数据属性?

There should be two Navigation Properties. 应该有两个导航属性。 EG 例如

[Display(Name="Trade Spend Type")]
[Column("TradeSpendID")]
[ForeignKey("PromotionTradeSpendType")]
public int? TradeSpendId { get; set; }
public virtual PromotionTradeSpendType PromotionTradeSpendType { get; set; }

[Display(Name = "Trade Spend Sub Type")]
[Column("TradeSpendSubID")]
[ForeignKey("PromotionTradeSpendSubType")]
public int? TradeSpendSubId { get; set; }
public virtual PromotionTradeSpendType PromotionTradeSpendSubType { get; set; }

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

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