OK, so I got to the end, and I think this is a bug in the Entity Framework, but I can get around this. That's what it is ...
The OneId column in Table Two had one place at the end.
Yup - go figure - how terribly unpleasant is it !?
So, I got out a sql script that made LTRIM(RTRIM( in each nvarchar column in the database, and everything works fine.
Now, given that the SQL server does not care about spaces (as proved in the query with the connection in the question), I donβt really like that the Entity Framework will take care, especially since it is completely strange and inconsistent here. Of course, the point at which I call Single to get the filled sdi variable should have been thrown out or the navigation property should be filled out - one or the other, but this behavior is just confused (in my opinion) - which has arbitrary property related to the price of the fish ?
Just for completeness, there is something here to reproduce it is really simple. Create a new database and then run this SQL script on it:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[One]( [OneId] [nvarchar](10) NOT NULL, [SomeInt] [int] NOT NULL, CONSTRAINT [PK_Delivery] PRIMARY KEY CLUSTERED ( [OneId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE TABLE [dbo].[Two]( [TwoId] [int] NOT NULL, [OneId] [nvarchar](10) NOT NULL, CONSTRAINT [PK_DeliveryItem] PRIMARY KEY CLUSTERED ( [TwoId] ASC, [OneId] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO INSERT INTO Two(TwoId, OneId) VALUES (1, '1 ') INSERT INTO One(OneId, SomeInt) VALUES ('1', 1.0)
Now create a C # console application, add a link to EntityFramework (version 4.3.1) and the System.Data.Entity assembly, paste this code and run it - it will print SHOULD NOT BE PRINTED!!! .
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Linq; namespace EFTest { public class Two { public int TwoId { get; set; } public string OneId { get; set; } public virtual One One { get; set; } } public class One { public string OneId { get; set; } public virtual ICollection<Two> Twos { get; private set; }
Then do one of the following:
- Comment on the
SomeInt property in class One - Exclude space in the database (
UPDATE Two SET OneId = RTRIM(OneId) ).
Or it will work (obviously, cropping is the only reasonable real fix).