I have the following models.
public class Site
{
public int Id { get; set; }
public string SiteName { get; set; }
public string SiteUrl { get; set; }
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
public class SiteBrand
{
public int Id { get; set; }
public int SiteId { get; set; }
public int BrandId { get; set; }
public SiteConfiguration SiteConfiguration { get; set; }
}
SiteBrand has a Foreign key on SiteId of Site.
I am trying to Update my Site entity in this way.
public bool Update(Site item)
{
try
{
if (item == null)
return false;
var itemToUpdate =
_dbContext.SiteConfigurations.FirstOrDefault(ua => ua.Id == item.Id);
if (itemToUpdate == null)
return false;
itemToUpdate.SiteName = item.SiteName;
itemToUpdate.SiteBrands = item.SelectedBrands.Select(
br =>
new DataEntities.Siteconfig.SiteBrand {BrandId = br}).ToList();
_dbContext.SaveChanges(); // Save changes.
return true;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
But above code is throwing the following 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.
I think I am getting this error because I am trying to update my Site entity with out clearing existing foreign key entries. I am not sure whether it is right or not and also I am not sure how to resolve this problem. Can somebody help me on this?
Thanks