Riz
Riz

Reputation: 6686

Can't easily set property to Null when editing an entity

In my asp.net core app with EF6, I have a hard time setting a property to Null. For example:

public Class A { public int Id {get; set;} public virtual B B{ get;set; } }
public Class B { public int Id {get; set;} }

//in edit method in controller:

var db_a = dbContext.A_entities
.Include(x => x.B) //if this line isn't there, then setting to null doesn't work
.Single(x => x.Id == form_a.Id);
if (form_a.B == null) {
 db_a.B = null; //this doesn't save to db unless we use .Include() above.
}

//...

dbContext.SaveChanges();

In the above, if I have 10 properties, or if B happens to have certain properties, then it becomes cumbersome to use .Include for every property. Is there a better way to do this?

Upvotes: 0

Views: 152

Answers (2)

Edward
Edward

Reputation: 30056

If you want to delete the relationship between A and B, you could try to define the foreignkey in A like

public class A
{
    public int Id { get; set; }
    public string AName { get; set; }
    public int? BId { get; set; }
    public virtual B B { get; set; }
}

And, then when deleting the relationship, you just need to set the BId as null

var a = _context.A.FirstOrDefault();
a.BId = null;
_context.SaveChanges();

Upvotes: 0

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

You are reaching B using foreign key (relation) through A, EF does a lazy loading and does not actually load all Bs for each A, using Include tell it to eager load B so it actually loads and you can set its value.

however if you don't need A and just want to set its B value to null do something like this:

var b = dbContext.A_entities.SingleOrDefault(x => x.Id == form_a.Id)?.B;
if (form_a.B == null) b = null; 

Upvotes: 1

Related Questions