jspk501
jspk501

Reputation: 11

Entity Remove() is setting foreign key properties to null

I have a One-to-Many relationship as shown below - the child in the relationship is soft-deleted and the string foreign key is non-nullable/[Required] however I'm having issues when I try to remove the child as EF is setting the foreign key id to null so when I SaveChangesAsync its throwing DbEntityValidationException because of the [Required] attribute as the Id is null thus invalidating the [Required] rule

I understand this is default behavior of EF to set the Id's to null but was wondering if there's a workaround in this scenario? One solution I had was to set the Id's again after Remove() which works fine but feels like a bit of a hack and unsure if this will have further implications

User:

[Key]
public string Id { get; set; }

Item:

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

[Required]
public string UserId { get; set; }

[ForeignKey("UserId")]
public User User { get; set; }

public bool IsDeleted { get; set; }

Removing the item:

var item = db.Items.Where(x => x.Id == ItemId).FirstOrDefault(); //item.UserId is not null here
db.Items.Remove(item); //item.UserId is now null after Remove
db.SaveChanges()

Current workaround:

db.Items.Remove(item); //item.UserId is now null after Remove
item.UserId = originalUserId //item.UserId is no longer null and will validate successfully
db.SaveChanges();

Upvotes: 0

Views: 1037

Answers (1)

Serge
Serge

Reputation: 43959

If you don't want to remove required, the only way is to assign the new user at first. It doesn't make any sense to keep required and not assign a new user

item.UserId=newUserId

after this you can remove previous User without any problem.

As a work around you can create a fake user with name "Deleted", and use it temporarily, but I really can' t see why do you need it. Why just dont remove requiered attribute?

Upvotes: 1

Related Questions