none
The relationship could not be changed because one or more of the foreign-key properties is non-nullable... RRS feed

  • Question

  • public class A {
    	public int ID { get; set; }
    	
    	public Int32? BValueID { get; set; }	
    	[ForeignKey("BValueID")]
    	public virtual B BValue { get; set; }
    }
    public class B {
    	public int ID { get; set; }
    	public string Value { get; set; }
    }

    When I try to execute:

    A a = dc.ATable.GetByKey(1); a.BValueID = 3; // B with ID 3 exists
    dc.Update(a); dc.SaveChanges(); // or A a = dc.ATable.GetByKey(1); a.BValue = dc.BTable.GetByKey(3); // B with ID 3 exists
    dc.Update(a); dc.SaveChanges(); // or A a = dc.ATable.GetByKey(1); a.BValueID = 3; // B with ID 3 exists a.BValue = dc.BTable.GetByKey(3); // B with ID 3 exists
    dc.Update(a); dc.SaveChanges();

    It throws an exception:

    The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

    Where dc.Update(a) is like:

    var oldEntity = Set.Find(entity.ID);
    var entry = dc.Entry(oldEntity);
    entry.CurrentValues.SetValues(entity);
    Friday, July 5, 2013 2:45 PM

All replies

  • Hi Tomasz,

    I tried to create the entities using Code First, but I'm not able to reproduce the problem.

    What is the GetByKey() method defined? I replace it by Find method in my application.

    Would you like to upload a demo project to reproduce the issue to SkyDrive if possible? We will have a research to see what is the problem.

    Best regards,


    Chester Hong
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help

    Tuesday, July 9, 2013 6:05 AM
    Moderator