【发布时间】:2021-07-08 18:02:02
【问题描述】:
将 EFCore 3.1 与库 EFCore.BulkExtensions 3.6.1(EFCore 3.1 的最新版本)结合使用。
数据库服务器为 SQL Server 2019。
这是重现错误的代码。
一个简单的 Customer 类,带有来自另一个类的导航属性:
public class Customer
{
public int ID { get; set; }
public String Name { get; set; }
public Cont Continent { get; set; }
}
public class Cont
{
public int ID { get; set; }
public String Name { get; set; }
}
当我尝试将实体插入到具有填充导航属性的客户中时 使用 EFCore.BulkExtension 库中的“BulkInsert”方法,导航道具的值不会保存到数据库中:
Customer cust1 = new Customer
{
Continent = contList.Find(x => x.Name == "Europe"),
Name = "Wesson Co, Ltd."
};
Customer cust2 = new Customer
{
Continent = contList.Find(x => x.Name == "Asia"),
Name = "Tiranha, Inc."
};
// (checking the "Continent" props here shows them to be properly populated)
List<Customer> CustomerList = new List<Customer> { cust1, cust2 };
dbContext.BulkInsert(CustomerList);
结果是数据库中的“ContinentID”列为NULL。
另一种方式,像往常一样使用 EF Core SaveChanges() 工作 - 将最后两行更改为:
dbContext.Customers.AddRange(cust1, cust2);
dbContext.SaveChanges();
这完全没问题。但是我必须插入一百万条记录,而 SaveChanges() 在这种情况下的表现很糟糕。
是不是我做错了什么?
使用 BulkExtension 的另一个(较低)版本没有帮助。更高版本将无法工作,因为它们都以 EFCore 5 和 NetStandard 2.1 为目标,而我的项目目前不支持。
在 EFCore.BulkExtension 文档中找不到任何提示或提及导航道具相关信息。
寻找正在发送的 SQL 只会向我显示这样的查询
INSERT INTO dbo.Customers (ContinentID, Name) VALUES @p1, @p2
因此,由 BulkExtensions.BulkInsert() 来正确放置值,但它似乎没有。
关键是类似的代码已经工作了 6 个月,现在对于任何版本的 BulkExtension 库来说,上面的简单场景都不会。所以很可能我的代码或我的方法有问题,但找不到。
更新
将包 EFCore.BulkExtensions 降级到 3.1.6 会给我一个不同的错误。仍然不起作用,但这是错误:
System.InvalidOperationException : The given value 'Customer' of type String from the data source cannot be converted to type int for Column 2 [ContinentID] Row 1.
----> System.FormatException : Failed to convert parameter value from a String to a Int32.
----> System.FormatException : Input string was not in a correct format.
【问题讨论】:
标签: ef-core-3.1 efcore.bulkextensions