我在 EF7 中有一个对象模型,看起来像这样:
Story -> StoryPhotos[]
我通过提交故事的表单来构建模型,用户还可以在其中附加 N 张照片。模型创建看起来像这样:
var story = new Story
{
// ...
StoryPhotos = myFormData.Photos.Select(p => new StoryPhoto {
Name = p.Name,
FileName = p.FileName,
etc.
}).ToList()
}
然后,一旦我建立了我的数据模型,我就通过存储库保存数据。
await repository.AddOrUpdateStoryAsync(story)
看起来像这样
if (story.Id == 0)
{
context.Stories.Add(story);
context.StoryPhotos.AddRange(story.StoryPhotos);
}
else
{
// Update properties for an edit.
}
await context.SaveChangesAsync();
这很好用...只要我只有一张 StoryPhoto。一旦我将多个元素放入数组中,就会出现此异常:
An unhandled exception occurred while processing the request.
SqlException: Incorrect syntax near ','.
System.Data.SqlClient.SqlCommand.<>c__DisplayClass16.<ExecuteDbDataReaderAsync>b__17(Task`1 result)
我的研究表明,关于 EF7 如何保存对象图存在一些不同的问题,但我对其中一个保存良好而多个保存不正确的情况感到困惑,并且没有对代码进行其他更改.
我正在使用 EntityFramework-SqlServer 7.0.0-beta7。
最佳答案
好吧,这就是答案。我也在response to the issue发帖了(这不是问题)在 ASP.NET 5 Entity Framework GitHub 上被跟踪。在这里为遇到它的任何人重复。
好的,我可以直接在我的 SQL 数据库上重现问题。这是正在生成的查询。
INSERT INTO [StoryPhoto] ([FilePath], [StoryId])
OUTPUT INSERTED.[Id]
VALUES ('path1', '174'),
('path2', '174'),
('path3', '174');
我得到这个错误:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near ','.
此外,为了找到这个,我用谷歌搜索了我原来的问题(当我第一次遇到这个问题时)并找到了 this post on SO其中包括这个答案:
In order to use the multi-row VALUES(),() syntax, you need to be running SQL Server 2008 (or newer).
Since you are running SQL Server 2005, you need to run separate insert statements, use UNION/UNION ALL, or upgrade the instance (which is separate from Management Studio, which is just a client tool you use to connect to instances running any number of versions of SQL Server).
所以,这是我在原帖中的怀疑。这个特定的应用程序仍在运行 SQL Server 2005。
这让我找到了 EntityFramework.MicrosoftSqlServer 支持的数据库版本,即 2008 年及更高版本。
关于entity-framework - 使用一个对象在 EF7 中保存数据 - 而不是使用多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136378/