繁体   English   中英

如何使用“数据库优先”建立一对一关系?

[英]How do I establish a one-to-one relationship using Database First?

生成模型时,许多关系会自动映射。 但是,某些关系是“不正确的”(或者至少不是我想要的)或丢失。

我毫不怀疑这是由于数据库设计不佳造成的,但是基于我在该项目中的角色,我无能为力。 但是,我可以在应用程序代码中做些什么来修复映射?

这是一个例子:

我想将StoreProductId属性映射到StoreProducts表。

桌子

ProductAttributePriceAdjustment

public partial class ProductAttributePriceAdjustment
{
        public int AdjustmentId { get; set; }
        public int StoreProductId { get; set; }
        public int StoreId { get; set; }
        public string ProductId { get; set; }
        public Nullable<int> ProductSizeId { get; set; }
        public Nullable<decimal> Adjustment { get; set; }
        public int PointsAdjustment { get; set; }
        public Nullable<int> ProductColorID { get; set; }

        public StoreProduct StoreProduct { get; set; }
}

店铺产品

public partial class StoreProduct
{
    public int StoreProductID { get; set; }
    public int StoreID { get; set; }
    public string ProductID { get; set; }
    public bool Featured { get; set; }
    public bool Clearance { get; set; }
}

在我看来,当我尝试调用以下内容时:

@adjustment.StoreProduct.ProductID

我收到此错误:

Object reference not set to an instance of an object.

更新1

我遵循了Frans的建议并将我的模型更新为:

public partial class ProductAttributePriceAdjustment
{
    public int AdjustmentId { get; set; }
    public int StoreProductId { get; set; }
    public int StoreId { get; set; }
    public string ProductId { get; set; }
    public Nullable<int> ProductSizeId { get; set; }
    public Nullable<decimal> Adjustment { get; set; }
    public int PointsAdjustment { get; set; }
    public Nullable<int> ProductColorID { get; set; }

    public virtual StoreProduct StoreProduct { get; set; }
}

但仍然出现相同的错误。

您不能在这样的实体框架中创建1:1映射。 不支持。

实体框架仅支持1:1映射,其中两个表都具有一个共享的主键(即它们具有相同的主键,并且其中一个是另一个的外键)。 在您所处的情况下,实际上是在创建1对1,因为不能保证StoreProductId是唯一的。

暂无
暂无

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

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