Previously no-tracking entities get tracked upon calling Savechages(). Is this normal?

M. Azyoksul

I have a simple controller in which I create and add a user and a profile to the database

    public async ActionResult AddUserAndProfile(string id)
    {
        _context.Users.Add(new User { Id = id });
        _context.SaveChanges(); // If this line is removed, error doesn't occur.

        var profile = new Profile
        {
            Id = "id",
            User = _context.Users.AsNoTracking().FirstOrDefault(u => u.Id.Equals(id))
        }; // Exception given on this line.
        _context.Profiles.Add(profile);
        _context.SaveChanges();

        return Ok();
    }

When I call this controller with id = "0" I get the following exception:

The instance of entity type 'User' cannot be tracked because another instance with the key value '{Id: 0}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.

However, if I remove the first SaveChanges() call, this error is not shown.

1st question: Is it intended that entities get tracked after saving changes, wouldn't it make sense that they get tracked beforehand only? Also afaik, add actions don't mark entities as tracked.

2nd question: When is the best time to call SaveChages() in this situation? (It is important to note that add user and add profile actions are in different repo methods in the real project. I simplified the code here.)

3rd question: What is the best way to add foreign keys in situations like this?

Guru Stron

You should be able to save whole hierarchy within one call to SaveChanges:

var profile = new Profile
    {
        Id = "id",
        User = new User { Id = id }
    }; 
_context.Profiles.Add(profile);
_context.SaveChanges();

It should answer 2nd and 3rd questions I think. As for the first one - there is a github issue with request to "Do not track after SaveChanges()".

Since you have different methods you can just set the UserId property on Profile (if you have explicitly added it to Profile entity) directly.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to release tracked entities?

Get the x and y pixel co-ordinates of the ROI that has been tracked in a tracking algorithm in OpenCV C++

How to ignore the contents of a previously tracked directory in git?

InvalidRequestException upon using get_query_results despite getting HTTPStatusCode: 200 when I ran start_query_execution previously

Entity framework : tracking entities by context

How do I get my DataBase First EF 6.1 Entities to become a change tracking proxies

How to start tracking previously ignored file?

Object tracking program does not show tracked points in the output image

OpenCV and Python: object tracking and saving the object being tracked as an image

Program exits upon calling await

How do I clear tracked entities in entity framework

HTML entities to normal strings in PHP

Why is HashMap not in normal form upon series of inserts?

How to get the name of the tracked image in Swift with RealityKit?

Calling two entities in return Ok()

How to avoid calling 'startx' upon ssh login

Change formatting of date upon calling value

Storing variables upon calling Higher Order Function

ArrayList method is creating an error upon calling

Dynamically calling upon similar objects in javascript?

Segment fault upon calling method of class

Associative entities and third normal form in a simple database

Stop tracking a file in git from a timepoint on while keeping old tracked commits

Get ActorRef to previously spawned EventSourcedBehavior

Get WiFi SSID upon connection

Navigation View starts with a gap then returns to normal upon scrolling; missing title

How to enable change tracking for ALL entities in Dynamics 365?

EF Core 2.1 [change tracking] - saving all related entities

EF6 not tracking changes on entities when using FindAsync