简体   繁体   中英

How can you control the order of SQL updates in EF6 DB model using TPT inheritance?

Given the following classes ...

public class BaseClass
{
    [Key]
    public int ID { get; set; }
    public DateTime LastUpdatedDate { get; set; }
}

public class InheritedClass : BaseClass
{
    public string RandomValue { get; set; }
}

... which are mapped to SQL tables tblBaseClass and tblInheritedClass respectively using a TPT inheritance strategy in EF6.

When I create a record using the following code ...

var newClass = new InheritedClass {
    RandomValue = "Some Random Text",
    LastUpdatedDate = DateTime.Now
};

dbContext.InheritedClasses.Add(newClass);
dbContext.SaveChanges();

... data is inserted into the tblBaseClass first and then tblInheritedClass. However when I update a record similarly using ...

var existingClass = dbContext.InheritedClasses.Find(someKeyValue);
existingClass.LastUpdatedDate = DateTime.Now;
existingClass.RandomValue = "Some Different Random Text";
dbContext.SaveChanges();

The tables are updated in reverse order (specifically, tblInheritedClass is updated and then tblBaseClass is updated).

Question

How can I specify that I want the base classes table to be updated first in this scenario? I am creating a trigger in the database on the inherited table to keep track of value changes, however I need to reference the date in the base table when I do so.

There is no way you can specify a save order

When you call SaveChanges, all entities are ordered from an internal order in the method “ProduceDynamicCommands” then sorted again by the method “TryTopologicalSort” which loop to add command with no predecessor left (if you add A and B and A depend of B, then B will be inserted before A)

There is no way you can specify an order unless you override A LOT of internal method (I had to do it to develop a BulkSaveChanges feature).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM