Checking for duplicate rows using Entity Framework in C# - c#

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.

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)

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.

Related

Entity Framework Update Table with only keys

I've got two keys, and want to update the foreign keys in a single query, without pulling it out first(for efficiency reasons)
In other words, I'm wondering if there's any way to run the following query with entity
UPDATE User_Conversation
SET LastReadMessageId = #lastReadMessageId
WHERE Id = #userConversationId
AND UserId = #currentUserId -- for security
You can use "Attach" function with State=Modified for fields that you want to update.
Check here for more information.

How to manage versioning of entities in Entity Framework?

We have an entity for which we want to save old versions as revisions, what is the best way to achieve this?
The current idea is to have two properties Id and Revision that combined makes up the primary key. I am not sure if this is the correct approach, and I have issues with how to get the database to generate the values - if I do not set them myself.
If I save a completely new entity I want both Id and Revision to be set. ´Id´ to the next id in order, and Revision to zero.
If I save a new version of an entity I would set the Id to the id of the entity I want to create a new revision of (together with all other values I might want to bring over to the new entity). I would like to leave the ´Revision´ property empty, and the database should then increment this and set it to the previous latest revision value + 1.
How can I achieve this functionality with entity framework? Can I achieve it with entity framework?
Edit
I have tried this setup in my DbContext implementation:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityDao>().HasKey(m => new { m.Id, m.Revision });
modelBuilder.Entity<EntityDao>().Property(m => m.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityDao>().Property(m => m.Revision).ValueGeneratedOnAdd();
}
But then I get this error:
Only one column per table can be configured as 'Identity'.
If I remove the ValueGeneratedOnAdd statement on the Revision property, the service is able to start. But then I get an error on save since Revision is null - unless I manually give it a value.
There was also an issue that I could not explicitly set the Id property when I had the ValueGeneratedOnAdd statement. I got the following error:
Cannot insert explicit value for identity column in table 'Entities' when IDENTITY_INSERT is set to OFF.
But I found this info on how to solve that:
explicit-values-generated-properties
As for me the better option would be to create another versions table where you can store all of the entity versions with the entity id foreign key. And when you create completely new entity you just put it in the main table, but when you modify entity you just store existing entity inside versions table with foreign key, and update your entity in the main table. With that approach you would have the main table with only last versions of entities, so you don't need to filter them on get. And versions table from where you always can get all the versions with timestamp and some additional info that you want to have.

How to update primary key value in entity framework?

I have table(and also entity in Entity Data Model) Person with following fields:
Name Type
SocialID String
FirstName String
LastName String
which SocialID is Primary Key. I want to update value of SocialID for each record. However when i try to update this field in Entity Framework I get following error:
The property 'SocialID' is part of the object's key information and cannot
be modified.
The code that i get above error is:
foreach (var p in Entity.Persons)
{
p.SocialID= p.SocialID + "00";
Entity.SaveChanges();
}
How I can do this??
As mentioned by the others, you can't do it in code. You will have to make your update in SQL. Either in a migration or directly in SQL Server Management Studio (or the equivalent if you're using a different database).
UPDATE Person -- Or 'Persons' if that's what your table is called
SET SocialID = SocialID + '00'
It will require a lot more work than this if you have other tables use this column as a foreign key (you'll have to drop the constraints first -- on all tables that reference your primary key -- then fix the data and recreate the constraints). Or as Moe said in the comments, you can set your foreign keys to cascade on update.
As per my knowledge primary key once generated cant be updated programatically,that defies the purpose of primary key.
It'll be better if you insert all your data again with new primary keys and delete old data.
Why would you want to change the primary key? Entity framework will be using that field to identify the object, you can't change its value while it is the primary key.
Based on the first answer I suggest you change the table Person to have its own primary key, let's say PersonID and mantain the SocialID as a foreign key to the Social table. If you need a person to have several Social records you may need to create other table to correspond the PersonId to several SocialId, removing the SocialId from the person table.

insert data in no identity number column

I have a table in my database.
This table has one column named A, the column is not entity or auto number, unique key or...
I created a model from my db with Entity Framework 4.1.
My code
using (var contex = new testEntities())
{
Table_1 t = new Table_1();
t.A = 1;
contex.Table_1.Add(t);
contex.SaveChanges();
}
I do not want to use the identity number or index in my table.
When I want to insert a row in it it gives me this error:
Unable to update the EntitySet 'Table_1' because it has a DefiningQuery and no
<InsertFunction> element exists in the <ModificationFunctionMapping> element to
support the current operation.
You either have to give the table a primary key (which you don't seem to want to do) or you need to provide a function to tell Entity Framework how data can be inserted into the database.
I would strongly suggest that you put a primary key on your table unless you have a very good reason for not doing this, and in all my years I can't think of many instances when I wanted a table without a primary key.
If you don't want the primary key at all, then you might find this article useful about using Stored Procs for INSERTing data into the database: http://msdn.microsoft.com/en-us/data/gg699321.aspx

EntitySet<T> in LINQ to SQL- using it and removing it

I've got a pair of tables in my database. One of which has a primary key (a simple numerical ID), the other has that ID as a foreign key.
The first table has suddenly gained an EntitySet<OtherTable>. If I add a new OtherTable() to this, is it automatically sent to the database, and the ID's linked up, etc, when I use SubmitChanges()?
Secondly, the relationship isn't many-to-one, it's one-to-one, a corresponding entry in the second table is optional and singular. As such, a container like EntitySet isn't really appropriate for this relationship. An OtherTable? would be a more appropriate representation. How can I inform LINQ to SQL of this?
Set Unique = true in the associaton properties. That should adjust it to being 1:1

Categories