1

Using Entity Framework 6.x. For some entities after I create a new instance of an entity object and populate it with data values, I would then like to be able to trigger a lookup on the database. I would like to see if a row exists with all the same values that where populated into the entity object and if it exists return the primary key.

It seems logical that there should be a standard way to do this built into the entity framework but I can't find it. It would be nice if there was a method that would just take any entity object and return the primary keys of any matching rows.

G.Bouch
  • 51
  • 3

2 Answers2

1

What's wrong with just doing a FirstOrDefault() filter to retrieve an entity with matching values?

var entity = new Entity { // initialize some properties }
var matched = dbContext.EntityTable.FirstOrDefault(x => x.PropA = entity.PropA && x.PropB = entity.PropB);

(Don't have EF on my machine right now, the actual access code is just psuedo)

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • This of course will work, but I'm looking for a more standard way that does not require hardcoding logic for every entity. – G.Bouch Jan 27 '16 at 18:03
  • Then the answer is no, the functionality you're looking for does not exist. It would be possible for you to build your own generic implementation that uses reflection on an entity type to see which properties are populated and then generate an expression based on those properties which you could then use inside of a FirstOrDefault – Jesse Carter Jan 27 '16 at 18:12
  • Thanks, I'm going to use reflection to build a SQL statement to do this look up. – G.Bouch Jan 27 '16 at 18:25
  • Hi Jesse, how can you make it keep your input and move the data to there instead while erasing the old entry? Is there anyway you can do with with LastOrDefault() or any other way? .FirstOrDefault() erases the input entry. How do you keep the newest input entry while erasing the first duplicate? – Chris Singleton Dec 06 '21 at 21:03
0

This is not possible. You have to create query with all data values that you want to check. Another option is to have checksum column that contains some hash from all values (without the primary key), then you can compute the hash from newly created entity and query database if entity with such hash exist.

Edit: Additionaly there is an option to create multi column Constraint in SQL Server (check this: Unique constraint on multiple columns), but it doesn't return primary key of duplicated row in a convenient way.

Community
  • 1
  • 1
  • Thank for confirming this, I didn't think this existed but I wanted to make sure. I hope that they add this in the future. I think that I will just need to create a dynamic SQL statement that has a where clause that contains all the values from the entity. I did consider a multi column unique constraint but as you noted it doesn't return the primary key of the existing row. – G.Bouch Jan 27 '16 at 18:11