当我尝试着先使用Entity Framework代码以及如何设置实体之间的关系时。当我尝试向数据库中插入(种子)某些数据时遇到了一个问题。我试图将一个产品对象插入到buys(订单)对象中。所购买的产品属性是虚拟的,表明它是导航属性。有没有其他方法可以达到我想要的目标?
我运行Add-Migration initial
并收到错误消息:
无法添加实体类型“购买”的种子实体,因为它已设置了导航“客户”。要播种关系,您需要将相关实体种子添加到“客户”并指定外键值{'customerID'}。考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'查看所涉及的属性值
下面是在数据上下文类中运行的种子方法。
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);
}
这是要提到的两个模型。
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; }
}
答案 0 :(得分:0)
Id字段是字符串,您不会在任何地方填充它们。在将对象传递给HasData()之前,尝试为这些ID播种。
示例:
var productType = new ProductType()
{
Id = Guid.NewGuid().ToString(), //If they are supposed to be GUIDs
typeName = "Operating System"
};