[英]Entity Framework 1:1 Relationship FK's
我之前曾問過類似的問題,但想發布一個更新的問題,並包括所有必要的代碼來說明:
我有2個實體; 購物車和購物者。 他們有1:1的關系。 有時候我不想加載nav屬性來讀取FK值。 我已經按如下所述創建了實體,並設置了購物車和購物者之間的關系(請參見下面的映射類),但是EF並未在實體上填充FK屬性(請參見下面的單元測試)。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ClassLibrary1
{
public class Cart
{
public int ID { get; set; }
public int ShopperID { get; set; }
public virtual Shopper Shopper { get; set; }
}
public class Shopper
{
public int ID { get; set; }
public int CartID { get; set; }
public virtual Cart Cart { get; set; }
}
public class CartMap:EntityTypeConfiguration<Cart>
{
public CartMap()
{
this.HasKey(t => t.ID);
// Properties
// Table & Column Mappings
this.ToTable("Cart", "Cart2");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.ShopperID).HasColumnName("ShopperID");
//this.HasRequired(t => t.Shopper)
// .WithRequiredPrincipal(t => t.Cart);
}
}
public class ShopperMap : EntityTypeConfiguration<Shopper>
{
public ShopperMap()
{
this.HasKey(t => t.ID);
// Properties
// Table & Column Mappings
this.ToTable("Shopper", "Cart2");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.CartID).HasColumnName("CartID");
//// Relationships
this.HasRequired(t => t.Cart)
.WithRequiredDependent(t => t.Shopper)
.WillCascadeOnDelete(true);
}
}
public class CartDbContext : DbContext
{
public IDbSet<Cart> Carts { get; set; }
public IDbSet<Shopper> Shoppers { get; set; }
public CartDbContext():base("name=CartTest")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new CartMap());
modelBuilder.Configurations.Add(new ShopperMap());
}
}
public class DBSeedingData : DropCreateDatabaseAlways<CartDbContext>
{
protected override void Seed(CartDbContext context)
{
var cart1 = new Cart{Shopper = new Shopper()};
var cart2 = new Cart {Shopper = new Shopper()};
base.Seed(context);
context.Carts.Add(cart1);
context.Carts.Add(cart2);
context.SaveChanges();
}
}
[TestClass]
public class TestClass
{
[ClassInitialize]
public static void RunOnceForAllTests(TestContext testContext)
{
Console.WriteLine("Initializing Database");
using (var ctx = new CartDbContext())
{
try
{
Database.SetInitializer(new DBSeedingData());
ctx.Database.Initialize(true);
Console.WriteLine("Database Dropped, Created & Seeded.");
}
catch (Exception ex)
{
throw ex;
}
}
}
[TestMethod]
public void CanReadAllCarts()
{
using (var ctx = new CartDbContext())
{
foreach (var cart in ctx.Carts)
{
Console.WriteLine(" actual: Cart Id: {0} Shopper Id: {1} Shopper's Cart Id: {2}", cart.ID, cart.ShopperID, cart.Shopper.CartID);
Assert.IsTrue(cart.ID > 0, "Cart PK was not set");
Assert.IsTrue(cart.ShopperID > 0, "Shopper FK in Cart was not set");
Assert.IsNotNull(cart.Shopper, "Failed to load navigation properties");
Assert.IsTrue(cart.Shopper.CartID > 0, "Cart FK in Shopper was not set");
}
}
}
}
}
我在這里想念什么? 我一直在努力解決這個問題一個星期。
我以前曾經經歷過,並且在EF中一對一進行時也遇到了麻煩。 我們進行了一項工作,其中兩個實體之間只有一個導航屬性。 在您的情況下,選擇是否將導航屬性放在Cart或Shopper類中。 基本上,這是EF中的映射,其中只有一側具有nav屬性。 缺點是沒有導航屬性的人是盲人的,您無法分辨出它與誰有關。 這是一篇關於它的文章 。
假設您將nav屬性放在Shopper類中
public class Cart
{
public int ID { get; set; }
// no nav property for Shopper
}
public class Shopper
{
public int ID { get; set; }
public int CartID { get; set; }
public virtual Cart Cart { get; set; }
}
然后您將其映射為:
public class ShopperMap : EntityTypeConfiguration<Shopper>
{
public ShopperMap()
{
// other mappings
// mapping to cart, notice that the WithMany() is empty
this.HasRequired(t => t.Cart)
.WithMany()
.HasForeignKey(t => t.CartID);
}
}
您會在文章中看到EF Code-First(或通常稱為EF)不支持一對一的外鍵關聯。 這項工作對我們有用,所以我希望對您也有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.