C
C#4w ago
lime_soft

Entity Framework Core updating tables in navigation fields

so in efcore lets say i have an entity Foo and Baz:
public class Foo
{
public int Id {get;set;}
public ICollection<Baz> Bazs {get;set}
}

public class Baz
{
public int Id {get;set;}
public string SomeOtherProp {get;set}
public int FooId {get;set}
}
public class Foo
{
public int Id {get;set;}
public ICollection<Baz> Bazs {get;set}
}

public class Baz
{
public int Id {get;set;}
public string SomeOtherProp {get;set}
public int FooId {get;set}
}
my question is if i try to update Foo how can i efcore to only update the FooId property in Baz if i pass Foo { Baz { Id: 1, FooId: 2 } }, i don't want Baz.SomeOtherProp to be null i just want it to stay the same
3 Replies
Yawnder
Yawnder4w ago
You either do a roundtrip to get Baz first, or you use ExecuteUpdate.
Keswiik
Keswiik4w ago
Alternatively, if you have Baz as a set on your dbcontext, you can instantiate a new instance of Baz and attach it, make your modification, then use SaveChanges() like normal.
var newBaz = new Baz() {
Id = someId
}
dbContext.Bazzes.Attach(newBaz);
// because you modify FooId after attaching, the change tracker detects FooId as the only modified field
newBaz.FooId = modifiedId;
dbContext.Save();
var newBaz = new Baz() {
Id = someId
}
dbContext.Bazzes.Attach(newBaz);
// because you modify FooId after attaching, the change tracker detects FooId as the only modified field
newBaz.FooId = modifiedId;
dbContext.Save();
Doing it like this can be useful if you have multiple entities to modify with unique values
Unknown User
Unknown User4w ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?