使用实体框架与两个外键定义的一对多关系
问题描述:
我正在使用现有数据库,因此更改模式不是一个选项。以下是我正在使用的表格...使用实体框架与两个外键定义的一对多关系
Product
-------------------------------------
ID - GUID [PK]
Name - varchar(100)
ModelId - GUID [FK1, FK2]
SoftWareVersion - varchar(10) [FK2]
[FK1] Foreign Key to Model table
[FK2] Foreign Composite key to SoftwareVersion table
ProductModel
-------------------------------------
ID - GUID [PK]
ModelName - varchar(100)
SoftwareVersion
-------------------------------------
ID - GUID [PK]
Version - varchar(10)
ModelId - GUID [FK1]
[FK1] Foreign Key to Model table
每个单独产品都安装有软件。我们有几种产品模型,每种产品都明显与单一模型(产品[FK1])相关联。
在每个产品型号的生命周期中,它可能有多个软件更新/版本。同样,该软件可能安装在许多型号上。
我需要能够采取的ProductID并返回安装在该特定产品的软件版本。通常我会得到与我正在查找的产品型号相关的软件版本,但型号可能有几个更新。我无法单独查找Product.SoftwareVersion字段,因为它会返回安装了该软件的所有不同模型。
所以,最后我需要在ModelId &版本匹配的产品,我望着从SoftwareVersion返回的记录。
我想返回SoftwareVersion作为产品的属性...
Product.SoftwareVersion
在我ProductEntity的定义,我有以下...
[Table("Product")]
public class ProductEntity
{
[ForeignKey("Model")]
public Guid ModelID { get; set; }
public virtual ProductModelEntity Model { get; set; }
[ForeignKey("SoftwareVersion")]
public String SoftwareVersionNumber { get; set; }
public virtual SoftwareVersionEntity SoftwareVersion { get; set; }
}
所以 “ModelID”为模型执行外键的角色,并作为SoftwareVersion的组合外键的一部分。我却无法分配多个ForeignKey的属性相同的属性...
[ForeignKey("Model"),ForeignKey("SoftwareVersion")]
public Guid ModelID { get; set; }
public virtual ProductModelEntity Model { get; set; }
我更愿意与更多钞票,如果属性的工作,但我开到其他技术也是如此。 (属性直接在相关代码中描述类,而不是在图书馆周围扩展定义,很好理解你在看什么,而不是花时间去追求定义......但我离题了!)
任何帮助一如既往是不胜感激。
谢谢
-G
答
我认为下面的注释都将工作:
[Table("Product")]
public class ProductEntity
{
public Guid ModelID { get; set; }
public String SoftwareVersionNumber { get; set; }
[ForeignKey("ModelID, SoftwareVersionNumber")]
public virtual ProductModelEntity Model { get; set; }
[ForeignKey("SoftwareVersionNumber")]
public virtual SoftwareVersionEntity SoftwareVersion { get; set; }
}
或者:
[Table("Product")]
public class ProductEntity
{
[ForeignKey("Model"), Column(Order = 1)]
public Guid ModelID { get; set; }
[ForeignKey("Model"), ForeignKey("SoftwareVersion"), Column(Order = 2)]
public String SoftwareVersionNumber { get; set; }
public virtual ProductModelEntity Model { get; set; }
public virtual SoftwareVersionEntity SoftwareVersion { get; set; }
}