0

I have the following code:

public void Remove(Guid id)
{

    var symbol = new Symbol()
                 {
                     Id = id
                 };
    _ctx.Entry(symbol).State = EntityState.Deleted;
    _ctx.SaveChanges();
}

The symbol entity has a related entity called "Category". It is not set up to cascade delete since it is a value from a lookup table. I want to leave the category alone, however when this runs it throws a DbUpdateException: Entities in 'HourlyContext.Symbols' participate in the 'Symbol_Category' relationship. 0 related 'Symbol_Category_Target' were found. 1 'Symbol_Category_Target' is expected.

I understand that EF is confused about what to do with the relationship, how can I tell it to simply discard the reference to the Category and go ahead and delete the Symbol?

Thanks.

.

EDIT

Okay so I tried making the foreign key nullable (FYI I am using code first Entity Framework) by adding a nullable CategoryId as shown here:

public class Symbol : EntityBase
{
    [Required]
    public string CompanyName { get; set; }

    public int? CategoryId { get; set; }

    [Required]
    public MarketCategory Category { get; set; }
}

However, after creating a migration and updating the database, this does not resolve the exception.

.

EDIT 2

Okay so it turns out that (looking back now it's obvious) that adding the 'required' attribute prevents the column from being nullable. Now my intention was to not allow the coder (i.e. me) from accidentally setting the relationship to null in code, but allow the framework to null it out when I delete the object via Id. It appears this cannot be done. So all I needed to do was to remove the required attribute (and leave out the 'categoryId' column).

Community
  • 1
  • 1
Bitfiddler
  • 3,942
  • 7
  • 36
  • 51

2 Answers2

0

there must be a foreign key relationship being generated by EF. Easy way to check is to use SQL sever managent Studio and check for dependencies on the table

Right click on table and select Show dependencies

phil soady
  • 11,043
  • 5
  • 50
  • 95
0

To do so, I think the foreign key column of Category table (SymbolId, whatever ...) Should be Nullable. The OndDelete action of your database table should be set null, too.

Then, EF can simply remove that symbol.

Amin Saqi
  • 18,549
  • 7
  • 50
  • 70