Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Navigation Property with Entity.CurrentValues.SetValues

I have a Kalem Entity with a collection of DigerKalemMaliyetleri property, which is a collection of MaliyetBirimi objects. DigerKalemMaliyetleri is of JSON type and stored at the same table as a JSON column.

public class Kalem
{
    public int Id { get; set; }
    [Column(TypeName = "json")]
    public ICollection<MaliyetBirimi> DigerKalemMaliyetleri { get; set; }
}
public class MaliyetBirimi
{
    public int? DovizCinsi { get; set; }
    public decimal? Maliyet { get; set; }
}

When I try to update entity with only DigerKalemMaliyetleri property changed:

DataContext.Entry<Kalem>(first).CurrentValues.SetValues(second);

SQL Update command isn't executed and database record is not updated.

How could I update the entity without explicitly setting DigerKalemMaliyetleri property?

Regards

like image 201
serkanz Avatar asked Jan 21 '26 09:01

serkanz


1 Answers

I had the same problem, you cann't actually use SetValues to update navigation property, you nead instead use DataContext.Update(YourNewObj) and then DataContext.SaveChanges();, or if you want to use SetValues approach, you need:

-Get the exist entry

Kalem existObj = DataContext.Kalems.Find(YourNewObj.Id);

-Loop in navigations of updating entry and the existing one to set the values of updating entry:

foreach(var navObj in DataContext.Entry(YourNewObj).Navigations)
 {
   foreach(var navExist in DatatContext.Entry(existObj).Navigations)
    {
     if(navObj.Metadata.Name == navExist.MetaData.Name)
       navExist.CurrentValue = navObj.CurrentValue;
    }
 }

-Update also changes of direct properties:

DataContext.Entry(existObj).CurrentValues.SetValues(YourNewObj);

-Save your Updating:

DataContext.SaveChanges();

You can also check if you need to load your Navigations before going in foreach loop, otherwise you will get an error. Please if you see beter scenario, correct me.

like image 111
Nb777 Avatar answered Jan 23 '26 19:01

Nb777



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!