Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

entity framework - Strategies for automatically flagging entities with custom column serialization logic as dirty?

I have a setup like the following:

public interface Discriminable
{
}

public interface Configurable
{
    public Discriminable Configuration { get; set; }
}

public class MyData : Configurable
{
    public Guid Id { get; set; }

    [Column(TypeName="jsonb")]
    public Discriminable Configuration { get; set; }

    public string Name { get; set; }
}

public class OtherData
{
    public Guid Id { get; set; }
    public MyData MyData { get; set; }
}

//
// Inside of my DbContext
//

modelBuilder
    .Entity<Configurable>()
    .Property((configurable) => configurable.Configuration)
    .HasConversion(
        (configuration) => MySerializationLogic(configuration),
        (json) => MyDeserializationLogic(json)
    );

//

I'm running into an issue right now where I can save and load data fine, so long as I manually force the entity to be marked as dirty. Either by simply scanning for all entities of type Configurable and then manually marking them as dirty, or by telling the change tracker in my procedural code that they're dirty - somewhat painstakingly.

This is necessary because the values inside instances of Discriminable aren't noticed by the change tracker and as such, won't queue the containing Configurable instances for updates by marking them as dirty.

Sadly, my current approach results in a problem in some scenarios, like when I add MyData to OtherData and then try to save it. Because the MyData instance is already in the change tracker, EF attempts to update twice and I end up getting this exception:

Database operation expected to affect 1 row(s) but actually affected 0 row(s).

My question at this point: Is there any way for me to lean on the change tracker to notice when values inside of my Discriminable instances have changed? Are there potentially any other techniques that I can use to avoid having to add manual state tracking throughout my procedural code?


I've also cross posted this to the Entity Framework Core github issue tracker.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...