通过Entity Framework 7(Release Candidate 1)添加(中)大量嵌套子实体存储了错误的实体 - >子实体映射。
重现问题的简化示例:
using (TestContext dbContext = new TestContext())
{
var nums = Enumerable.Range(1, 40);
var orders = nums.Select(s => new TestOrder()
{
name = s.ToString(),
TestOrderItem = nums.Take(10).Select(o => new TestOrderItem()
{
name = (s*100 + o).ToString(),
TestOrderPricing =
new[] {new TestOrderPricing() {amount = (s*100 + o), PricingType = "Principal"}}.ToList()
}).ToList()
});
dbContext.AddRange(orders);
dbContext.SaveChanges();
}
执行该操作后,将存储所有关系 - 但大多数TestPricing实体都引用了错误的TestOrderItem实体。
这是实体框架RC1的现有错误还是设置错误?
测试环境的设置:
1)数据库优先 - 创建3个表:
CREATE TABLE [dbo].[TestOrder](
[OrderId] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](100) NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[TestOrderItem](
[OrderItemId] [int] IDENTITY(1,1) NOT NULL,
[OrderId] [int] NOT NULL,
[name] [varchar](100) NULL,
CONSTRAINT [PK_OrderItem] PRIMARY KEY CLUSTERED
(
[OrderItemId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[TestOrderPricing](
[OrderItemId] [int] NOT NULL,
[PricingType] [varchar](20) NOT NULL,
[amount] [decimal](18, 2) NULL,
CONSTRAINT [PK_OrderPricing] PRIMARY KEY CLUSTERED
(
[OrderItemId] ASC,
[PricingType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[TestOrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
REFERENCES [dbo].[TestOrder] ([OrderId])
ON DELETE CASCADE
ALTER TABLE [dbo].[TestOrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
ALTER TABLE [dbo].[TestOrderPricing] WITH CHECK ADD CONSTRAINT [FK_OrderPricing_OrderItem] FOREIGN KEY([OrderItemId])
REFERENCES [dbo].[TestOrderItem] ([OrderItemId])
ON DELETE CASCADE
ALTER TABLE [dbo].[TestOrderPricing] CHECK CONSTRAINT [FK_OrderPricing_OrderItem]
2)支持模型
dnx ef dbcontext scaffold "Server=.;Database=Test;Trusted_Connection=True;" EntityFramework.MicrosoftSqlServer --outputDir Models
3)运行示例
或下载包含映射的控制台应用程序:
https://onedrive.live.com/redir?resid=352A0129BF9CBD17%2134155
观察:
entity.Property(e => e.OrderItemId).UseSqlServerIdentityColumn()
(未通过脚手架添加)无效答案 0 :(得分:1)
RC1中的确认问题,已验证此问题已在工作代码库中修复,修复程序将在RC2中发布