2015-10-14 31 views
3

我有EF7一個對象模型看起來是這樣的:數據在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。

+0

當處理ORM時,SQL語法異常肯定是一個錯誤 – haim770

+0

@ haim770我想知道(尤其是考慮測試版狀態)。但是,當然,歷史告訴我,我不應該首先責怪圖書館。我將在明天在Github上查看源代碼作爲另一個途徑。如果有人能給我另一個想法,我會留下問題。 – JasCav

+0

您的代碼似乎沒有任何問題。現在EF 7 beta 8已經發布,您可以嘗試升級到該版本,以查看是否可以解決問題。 – htuomola

回答

0

那麼,這裏是答案。我還發布了它在response to the issue(這不是問題)在ASP.NET 5實體框架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 ','. 

此外,能夠找到這一點,我Google了我原來的問題有點不同(當我第一次碰到這種跑法),結果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年和更高版本。