[英]Entity Framework does not seed entity relationship
当我试图了解实体框架代码优先以及如何设置实体之间的关系时。 当我尝试将一些数据插入(种子)到我的数据库中时,我遇到了一个问题。 我正在尝试在购买(订单)object 中插入产品 object。 购买的那个产品属性对state是一个导航属性是虚拟的。 是否有不同的方式来实现我想要实现的目标?
我运行Add-Migration initial
并收到错误消息:
无法添加实体类型“购买”的种子实体,因为它设置了导航“客户”。 要为关系播种,您需要将相关实体种子添加到“客户”并指定外键值 {“customerID”}。 考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”查看涉及的属性值
下面是在数据上下文 class 中运行的播种方法。
private void SeedDatabase(ModelBuilder builder)
{
// Construct Data
var productType = new ProductType()
{
typeName = "Operating System"
};
var product = new Product()
{
typeID = productType.typeID,
productName = "Windows",
productVersion = "10 Home",
productDescription = "This version of windows is the Home 10 edition",
keyPrice = 10,
license = "ASDEW-2342-SDE34-FGR35",
ProductType = productType
};
var customer = new Customer()
{
customerEmail = "test-customer@gmail.com",
customerFullname = "John Derek"
};
var transaction = new Transaction()
{
paid = true,
transactionAmount = 10
};
var order = new Buys()
{
customerID = customer.customerID,
TransactionID = transaction.transcationID,
quantity = 1,
Date = new DateTime().Date,
Transaction = transaction,
Customer = customer,
Product = product,
productID = product.productID
};
transaction.Buy = order;
System.Collections.Generic.List<Buys> orders = new System.Collections.Generic.List<Buys>() { order };
product.customerBuys = orders;
builder.Entity<ProductType>()
.HasData(productType);
builder.Entity<Product>()
.HasData(product);
builder.Entity<Customer>()
.HasData(customer);
builder.Entity<Transaction>()
.HasData(transaction);
builder.Entity<Buys>()
.HasData(orders);
}
这里是提到的 2 个模型。
public class Customer
{
public Customer()
{
customerID = Guid.NewGuid().ToString();
}
[Key]
public string customerID { get; set; }
public string customerFullname { get; set; }
public string customerEmail { get; set; }
public virtual ICollection<Buys> customerBuys { get; set; }
}
// This is a join table between product and customer.
// Product can have many customers
// One customer can purchase many products
public class Buys
{
public Buys()
{
buyID = Guid.NewGuid().ToString();
}
[Key]
public string buyID { get; set; }
public string productID { get; set; }
public virtual Product Product { get; set; }
public string customerID { get; set; }
public virtual Customer Customer { get; set; }
public int quantity { get; set; }
public DateTime Date { get; set; }
public string TransactionID { get; set; }
public virtual Transaction Transaction { get; set; }
}
Id 字段是字符串,您不会在任何地方填充它们。 在将 object 传递给 HasData() 之前尝试播种这些 ID。
例子:
var productType = new ProductType()
{
Id = Guid.NewGuid().ToString(), //If they are supposed to be GUIDs
typeName = "Operating System"
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.