0

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

Jasonw
  • 5,054
  • 7
  • 43
  • 48
Naresh
  • 2,667
  • 13
  • 44
  • 69
  • Does it work if you remove `itemToUpdate.SiteBrands = item.SelectedBrands ...` or change it to `itemToUpdate.SiteBrands = item.SelectedBrands;`? – Garrett Fogerlie Sep 13 '12 at 16:59

1 Answers1

0

Problem is you aren't assigning a value to your SiteId foreign key so it will be sent to the DB as null (which your DB relationship doesn't allow). Try changing your code to:

itemToUpdate.SiteBrands = item.SelectedBrands
                              .Select(br => new DataEntities.Siteconfig.SiteBrand
                                            {
                                                SiteId = item.Id,
                                                BrandId = br
                                            }).ToList();
James
  • 80,725
  • 18
  • 167
  • 237