Reputation: 31
In the code below the value of item1 is null, while item2 is not null. Any ideas why Find method does not work properly in this case?
context= new EFModel.InputContext();
context.Items.Add(new Item{ Id = 1 });
var item1 = context.Items.Find(1);
var item2 = context.Items.Local.SingleOrDefault(i => i.Id == 1);
EDIT:
Thanks to @Maximc for pointing to the right direction. Apparently the issue was not the fact that the key was set to be auto generated and I assigned it. Somehow EF handles this situation properly by overwriting the aut generated Id with the user specified one. The problem was due to improper casting. My Id attribute is of type long
so when I do var item1 = context.Items.Find((long)1);
then it works.
Upvotes: 3
Views: 3912
Reputation: 1762
Does the Id has the attribute [Key] ? I think this will be your issue.
EDIT:
After reading your comment, something you are saying here is false, you say Id is auto generated, (StoreGeneratedPattern="Identity") but then at the codeexample you use:
context.Items.Add(new Item{ Id = 1 });
Assiging a value to a Auto generated property will cause problems I think, anyway you shoudn t do that (Id = 1), just use:
context.Items.Add(new Item()); // the Id will be auto genereated since it has storeGeneratedPattern="Identity"
Then try to use Find again, also I think find will only work if there is only 1 item in the list, while if you force the Id (1) and there 2 Items with Id: 1 (Which I find strange, think there should be an error), then FirstOrDefault Will still work! (since it will just look for the first one and then return it. You should try, SingleOrDefault, here it will check if it found a item with that Id or there more then just 1, then it will return also null.
Hope you can solve it now :).
Upvotes: 1