I can't figure it out, threads are in every way SO, I am doing everything right, but obviously I must have missed something ...
Given these two defs objects ...
public class Invoice { [Key] public int Id { get; set; } [ForeignKey("Block")] public int? BlockingCodeId { get; set; } public virtual BlockingCode Block { get; set; } ... } public class BlockingCode { [Key] public int Id { get; set; } public virtual ICollection<Invoice> Invoices { get; set; } ... }
And then the context with the appropriate relationship configuration ...
public class FaureciaContext : EFDataContext { public virtual DbSet<Invoice> Invoices { get; set; } public virtual DbSet<BlockingCode> BlockingCodes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Invoice>() .HasOptional(e => e.Block) .WithMany(e => e.Invoices); } }
Why, when I do this ...
// assume this invoice has a BlockingCode relationship var invoice = db.Invoices.First(); invoice.BlockingCodeId = null; db.Savechanges();
I get this exception ...
The operation failed: the relationship cannot be changed because one or more properties of the foreign key are not NULL. When a change is made to a relation, set the property of the foreign key associated with it to zero. If the foreign key does not support null values, a new relation must be defined, the property of the foreign key must be assigned a different nonzero value, or an object not associated with it must be deleted.
EDIT:
I thought I would add, since the answer here does not actually indicate a real answer to the problem I had ...
It turned out that this link was not a problem on which I actually updated another child property of the invoice class beyond the code, for example, in this way.
invoice.Lines = MergLines(newVersion, dbVersion);
My merge code worked fine, but since any favorite EF user would know that you can't just “replace the child collection” in this way, you need to delete the old one and add a new one if necessary.