1

In an Web application that uses Entity Framework 6 in a disconnected model I have a two tables that have a one-to-one relationship:

Borrower Table

  • BorrowerId (PK and FK)
  • BusinessName
  • [Other Columns removed to keep example simple]

BorrowerIndividual Table

  • BorrowerId (PK and FK)
  • FullName
  • [Other Columns removed to keep example simple]

The FK relationship is on BorrowerId. There is always a Borrower record, but only occasionally a BorrowerIndividual record. I have Cascade Delete defined on the relationship.

In Code I have following (I've removed the properties to keep the example simple):

[Serializable]
public class BusinessBorrower
{
  [Key]
  [Column("BusinessBorrowerId")]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int? Id { get; set; }

  [Required]
  public string BusinessName { get; set; }
}

[Serializable]
public class BusinessBorrowerIndividual
{
  [Key]
  [Column("BusinessBorrowerId")]
  [DatabaseGenerated(DatabaseGeneratedOption.None)]
  public int? Id { get; set; }

  [Required]
  public string FullName { get; set; }
}

In my repository class I have the following CRUD actions:

public class BusinessBorrowerRepository
{
    public Borrower GetById(int id)
    {
        Borrower item;

        using (var db = new MainContext())
        {
            item = db.Borrowers
                        .Include(b => b.BorrowerIndividual)
                        .FirstOrDefault(f => f.Id == id);
        }

        return item;
    }

    public int Add(Borrower entity)
    {
        int id;

        using (var db = new MainContext())
        {
            db.Entry(entity).State = EntityState.Added;

            db.SaveChanges();

            id = (int)entity.Id;
        }

        return id;
    }

    public bool Update(Borrower entity)
    {
        using (var db = new MainContext())
        {
            if (entity.BorrowerIndividual != null)
            {
                entity.BorrowerIndividual.Id = entity.Id; // share same key, set to match

                // Test if record exists in db to determine if added or modified
                var exists = db.BorrowerIndividuals.Any(i => i.Id == entity.BorrowerIndividual.Id.Value);
                db.Entry(entity.BorrowerIndividual).State = exists ? EntityState.Modified : EntityState.Added;
            }

            db.Entry(entity).State = EntityState.Modified;

            db.SaveChanges();
        }

        return true;
    }

    public bool Delete(int id)
    {
        using (var db = new MainContext())
        {
            var entity = GetById(id);

            if (entity.BorrowerIndividual != null)
            {
                db.BorrowerIndividuals.Attach(entity.BorrowerIndividual);
                db.BorrowerIndividuals.Remove(entity.BorrowerIndividual);
                entity.BorrowerIndividual = null;
            }

            db.Borrowers.Attach(entity);
            db.Borrowers.Remove(entity);

            db.SaveChanges();
        }

        return true;
    }
}

DbContext class:

internal class MainContext : DbContext
{
   internal MainContext() : base("name=SqlServer")
   {
     Database.SetInitializer<MainContext>(null);
   }

   public virtual DbSet<Borrower> Borrowers { get; set; }
   public virtual DbSet<BorrowerIndividual> BorrowerIndividuals { get; set; }

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
   {
     Database.SetInitializer<MainContext>(null); 

     modelBuilder.Configurations.Add(new BorrowerConfiguration());

     base.OnModelCreating(modelBuilder);
   }
}

class BorrowerConfiguration : EntityTypeConfiguration<Borrower>
{
  internal BusinessBorrowerConfiguration()
  {
    this.HasRequired(x => x.BorrowerIndividual).WithRequiredPrincipal();   
  }
}

The GetById and Add seem pretty typical. The Update and Delete seem overly verbose. Is there is something I can do that allow:

  1. The Update to work by just setting "db.Entry(entity).State = EntityState.Modified" without having to set the state of BorrowerIndividual?
  2. Is there a way to perform a more simple delete that will cascade without explicitly removing BorrowerIndividual?

Overall it just seems like there is more work than needed to get this to work.

4
  • With cascade delete, the Delete method for sure can be simplified by not using GetById, but something similar using the db variable or just a stub entity. For Update you have no other choice because you are receiving detached object.
    – Ivan Stoev
    Mar 3, 2017 at 19:30
  • I tried not using GetById and just attaching to a new instance of the object with just Id. The problem is when is I got a FK error when I saved because of the related BorrowerIndividual row needs to be removed first. I also had to add the entity.BorrowerIndividual = null line, otherwise it would could complain on SaveChanges. It seems like more work then it should be. I have a parent object that has this object as a property, and other children as well, so the Updates and Deletes are very long. Might make more sense to create Stored Procs, which would respect the Cascade Delete in SQL.
    – Josh
    Mar 3, 2017 at 21:43
  • 1
    Both db.Entry(new Borrower { Id = id }).State = EntityState.Deleted; and var entity = db.Borrowers.FirstOrDefault(e => e.Id == id); db.Borrowers.Remove(entity); work for me. But note that by the posted setup cascade delete was not activated, I had to add .WillCascadeOnDelete() after the WithRequiredPrincipal() call.
    – Ivan Stoev
    Mar 3, 2017 at 22:35
  • 1
    @IvanStoev, that did cleanup the delete! Since I haven't got any other feedback on the Update, if you post this as answer I can accept it since it cleaned up my Delete.
    – Josh
    Mar 4, 2017 at 15:57

1 Answer 1

1

Both methods can be simplified. But first make sure the cascade delete is turned on (because by default it isn't):

modelBuilder.Entity<Borrower>()
    .HasRequired(x => x.BorrowerIndividual)
    .WithRequiredPrincipal()
    .WillCascadeOnDelete();

Now the methods in question.

Delete:

Since you are using short live specifically allocated DbContext, you could use so called stub entity:

db.Entry(new Borrower { Id = id }).State = EntityState.Deleted;
db.SaveChanges();

But note that it will fail with exception if there is no record with the specified Id. So a safer version would be like this (do not use GetById method which uses different context, also don't Include the related data since we will be relying on the database cascade delete):

var existing = db.Borrowers.FirstOrDefault(e => e.Id == id);
if (existing == null) return; // ??
db.Borrowers.Remove(existing);
db.SaveChanges();

Update:

var existing = db.Borrowers.Include(e => e.BorrowerIndividual).FirstOrDefault(e => e.Id == entity.Id);
if (existing == null) return; // ??
db.Entry(existing).CurrentValues.SetValues(entity);
existing.BorrowerIndividual = entity.BorrowerIndividual;
db.SaveChanges();

This works in all scenarios of BorrowerIndividual modification (null to new - does INSERT, existing to null - does DELETE, existing to existing - does UPDATE). The only drawback is that in the last case it always generates UPDATE command for the BorrowerIndividual even if no property is changed. So if you want to optimize the database commands with a cost of a few more code lines, you could use this instead:

var existing = db.Borrowers.Include(e => e.BorrowerIndividual).FirstOrDefault(e => e.Id == entity.Id);
db.Entry(existing).CurrentValues.SetValues(entity);
if (existing == null) return; // ??
if (existing.BorrowerIndividual != null && entity.BorrowerIndividual != null)
{
    entity.BorrowerIndividual.Id = existing.Id;
    db.Entry(existing.BorrowerIndividual).CurrentValues.SetValues(entity.BorrowerIndividual);
}
else
    existing.BorrowerIndividual = entity.BorrowerIndividual;
db.SaveChanges();

Working with disconnected entities have never been easy in EF.

5
  • do you have a suggestion for a better ORM for ASP.NET MVC to SQL? I've used EF on about 6 applications over the last 4 years, before EF I used MS Enterprise Library Data Access Application Block and stored procs. EL isn't really an ORM, but I did save a bunch of repetitive ADO.NET calls. Although there is still a bunch of mindless repetitive work building CRUD stored procs, and and mapping all the properties.
    – Josh
    Mar 4, 2017 at 17:13
  • No. The only competitive is NHibernate, but IMO EF is more intuitive. The querying part is fine, and CRUD will tracking services of the context is easy. The only difficult is CRUD with disconnected entities / DTOs, but with some repetitive code everything can be resolved. There is a open source package GraphDiff which is addressing the last, but unfortunately it is not supported anymore.
    – Ivan Stoev
    Mar 4, 2017 at 17:22
  • I tried the second suggestion for update but it throws the following exception: An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code Additional information: The property 'Id' is part of the object's key information and cannot be modified. on the following line: db.Entry(existing).CurrentValues.SetValues(entity);
    – Josh
    Mar 4, 2017 at 17:36
  • I figured it out, Need to filter the record: var existing = db.Borrowers.Include(e => e.BorrowerIndividual).FirstOrDefault(e => e.Id == entity.Id); I updated your answer to reflect this change.
    – Josh
    Mar 4, 2017 at 17:42
  • Absolutely - that's exactly what I had in mind and tested before posting, but forgot to put it in the answer. Thanks for doing the update!
    – Ivan Stoev
    Mar 4, 2017 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.