Reputation: 6911
I'm working on an angular/breeze web app with EF code first, and run into a strange problem. Here is the code snippet:
public class Person
{
public int Id { get; set; }
public int? AddressId { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
// DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>().HasOptional(x => x.Address).WithMany(x => x.Persons).WillCascadeOnDelete(false);
base.OnModelCreating(modelBuilder);
}
Everything runs fine except one case: You can create a Person without specifying an address, however, once you select an address for the person, you can change to another one, but you can't remove it.
This is how I remove it in Angular select:
<option value=""></option>
This is the error I got when trying to reset the address:
{"The UPDATE statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Person_dbo.Address_AddressId\". The conflict occurred in database \"MyDb\", table \"dbo.Address\", column 'Id'.\r\nThe statement has been terminated."}
So, what's wrong?
UPDATE: As I figured out, the problem seems to be on the client side. When an empty option is selected, it sets the AddressId to 0, instead of NULL. If I change it to NULL in debug mode, it would work. This is the complete select code:
<select ng-model="person.address" ng-options="g.name for g in addressList"><option value=""></option></select>
Now, the question is that how can I make it return its id as NULL instead of 0 in case an empty address is selected?
Upvotes: 0
Views: 316
Reputation: 17863
Can you set up a plunker?
It seems to me that the Person.addressId
should be flagged as nullable in the metadata (can you confirm?) and therefore Breeze should set addressId
to null
(not 0
) when you null the Person.address
.
I have a feeling this may be an Angular issue involving your combobox binding option, <option value=""></option>
. I'm not sure that is doing what you think it is doing when used in combination with ng-options="g.name for g in addressList"
.
You might consider placing a "button" ('x' for "clear") next to the combobox that, when clicked, sets Person.address = null
or Person.addressId = null
.
Upvotes: 1