Automatically update ID value for records retrieved

c# entity-framework entity-framework-6

Question

So, consider the following class:

public class Solution
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
}

And the following methods

public void DoSomething()
{
    new Item originalItem = new Item();
    item.Name = "Test";

    InserIntoDb(originalItem);

    Assert.True(item.Id != 0);
}

public void InserIntoDb(Item item)
{
    context.Item.Add(item);
    context.SaveChanges();
}

On this case, after insert into the db, EF automatically updates the originalItem with its auto generated ID value.

My problem starts when I add some logic to only add to the db if the Name doesn't exist. If exists the Insert doesn't happen therefore the ID property is not populated.

My question is: Is there a way to make the context.Item (when retrieving all) to automatically update the ID of the originalItem value without having to change the InsertIntoDb method to return an Item and consequently having to add a line like

originalItem = InsertIntoDb(originalItem);

Thanks, in advance

1
1
9/21/2018 6:58:51 PM

Popular Answer

Nope, there is no built in way to update the item with the id from the db if it exists.

You will have to implement a custom approach to make this work. If this is only a small or single amount of items at once, then just attempt to get the named item from the database prior to entry and then for the one(s) not present insert.

If you are doing this for a large batch of items (more than 5000), consider using a stored procedure to do this work on the db server side for query performance.

0
9/21/2018 6:58:31 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow