Search code examples
c#visual-studioentity-frameworkscaffolding

Trying to delete record but EntityState.Deleted deletes all records


I'm trying to delete a record if it exists or add it if it doesn't. The adding works fine but if I have three records with the same Id but three different FavId even though Dtl shows the correct record it still deletes all three. I've tried various switching around but with the same end result.

using (var context = new DataContext())
{
    var query = from st in context.Favourites
                where st.Id == id && st.FavId == fav_id
                select st;
            
    var Dtl = query.FirstOrDefault<FavouritesModel>();
    if (Dtl != null)
    {
        var favDetails = new FavouritesModel { Id = id, FavId = fav_id };
        context.Entry(favDetails).State = EntityState.Deleted;
    } 
    .
    .
}

The model looks like this and there are only three fields with Id as primary key although FavId should be a key value too but I don't think that's why it is failing.

public partial class FavouritesModel
{
    public string Id { get; set; } = null!;

    public string FavId { get; set; } = null!;

    public string Name { get; set; } = null!;
}

Can someone who may have had this problem tell me what I have missed so that I can just delete the required record and not all of them.


Solution

  • I sorted the problem by adding FavId as a primary key along with Id, so no changes necessary just a change to my SQL DB.