我有两个表,它们来自旧系统。这些表从两个单独的外部源定期更新,并且仅用作我的应用程序中查找数据的“只读”表:
送货地点
public partial class DeliverySite
{
public string CustomerID { get; set; } // PK
public string CustomerName { get; set; }
public string DeliveryAddress { get; set; }
public string BillingAddress { get; set; }
//... fields removed for clarity.
// Navigational Properties.
public virtual ICollection<Item> Items { get; set; }
}
public class DeliverySiteMap : EntityTypeConfiguration<DeliverySite>
{
public DeliverySiteMap()
{
// Primary Key
this.HasKey(t => t.CustomerID);
// Properties
this.Property(t => t.CustomerID)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.CustomerName)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.DeliveryAddress)
.IsRequired();
this.Property(t => t.BillingAddress)
.IsRequired();
// Table & Column Mappings
this.ToTable("DeliverySites");
this.Property(t => t.CustomerID).HasColumnName("CustomerID");
this.Property(t => t.CustomerName).HasColumnName("CustomerName");
this.Property(t => t.DeliveryAddress).HasColumnName("DeliveryAddress");
this.Property(t => t.BillingAddress).HasColumnName("BillingAddress");
}
}
项目
public partial class Item
{
public string Item { get; set; } // PK
public string ItemDescription { get; set; }
public decimal Brand { get; set; }
public decimal Price { get; set; }
public string CustomerID { get; set; } // PK + FK
//... fields removed for clarity.
// Navigational Properties.
public virtual DeliverySite DeliverySite { get; set; }
}
public class ItemMap : EntityTypeConfiguration<Item>
{
public ItemMap()
{
// Primary Key
this.HasKey(t => new { t.Item, t.CustomerID });
// Properties
this.Property(t => t.UserItem)
.HasMaxLength(50);
this.Property(t => t.UserItemDescription)
.HasMaxLength(255);
this.Property(t => t.CCItem)
.IsRequired()
.HasMaxLength(50);
this.Property(t => t.CCItemDescription)
.IsRequired()
.HasMaxLength(255);
this.Property(t => t.CustomerID)
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("Items");
this.Property(t => t.Item).HasColumnName("Item");
this.Property(t => t.ItemDescription).HasColumnName("ItemDescription");
this.Property(t => t.Brand).HasColumnName("Brand");
this.Property(t => t.Price).HasColumnName("Price");
this.Property(t => t.CustomerID).HasColumnName("CustomerID");
}
}
鉴于这些表是独立更新的,可能为“DeliverySites”输入的“项目”不存在。
因此,我想建立一个可选的关系。(所以我可以在我的应用程序中使用导航属性,但这样我就不会阻止表格被独立更新。)
在我的范围内,我ItemMap : EntityTypeConfiguration<Item>
尝试了以下方法:
this.HasOptional(x => x.DeliverySite)
.WithMany(x => x.Items)
.HasForeignKey(x => x.CustomerID)
.WillCascadeOnDelete(false);
但我收到此错误:
System.Data.Entity.Edm.EdmAssociationType::多重性与关系“Item_DeliverySite”中角色“Item_DeliverySite_Target”中的引用约束冲突。因为从属角色中的所有属性都不可为空,所以主体角色的多重性必须为“1”。
我应该如何实现这种关系?
此外,如果我可以在不在数据库中添加任何 FK 约束的情况下做到这一点,那将是理想的。这可能吗?