I have a little problem saving data in the database. In a given method, I make a request to an API, serialize the data, and try to save to the database, as shown in the image, but I end up getting an error referring to the application's DataContext, saying:
System.InvalidOperationException: The instance of entity type 'Launch ' cannot be tracked because another instance with the same key value for {'id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Any tips on how to resolve this issue?
Save Database Method
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;
using RestSharp;
using SpaceFlightApiChallenge.Data.Context;
using SpaceFlightApiChallenge.Domain.Entities;
namespace SpaceFlightApiChallenge.Data
{
public class DatabaseImport
{
private readonly SpaceFlightContext _context;
public DatabaseImport(SpaceFlightContext context)
{
_context = context;
}
public async Task ImportData()
{
string url = "https://api.spaceflightnewsapi.net/v3/";
var client = new RestClient(url);
var apiRequest = new RestRequest("articles", Method.Get);
apiRequest.AddHeader("Accept", "application/json");
var response = await client.ExecuteAsync(apiRequest);
var content = response.Content;
var articles = JsonConvert.DeserializeObject<List<Article>>(content);
_context.Articles.AddRange(articles);
await _context.SaveChangesAsync();
}
}
}
Article Class
using System.Collections.Generic;
namespace SpaceFlightApiChallenge.Domain.Entities
{
public class Article
{
public int id { get; set; }
public bool featured { get; set; }
public string title { get; set; }
public string url { get; set; }
public string imageUrl { get; set; }
public string newsSite { get; set; }
public string summary { get; set; }
public string publishedAt { get; set; }
public List<Launch> launches { get; set; }
public List<Event> events { get; set; }
}
}
Launch Class
namespace SpaceFlightApiChallenge.Domain.Entities
{
public class Launch
{
public string id { get; set; }
public string provider { get; set; }
}
}
Event Class
namespace SpaceFlightApiChallenge.Domain.Entities
{
public class Event
{
public string id { get; set; }
public string provider { get; set; }
}
}
EDIT: I believe the whole problem is with the id's. All objects that the external API returns me (Article, event, launch) have their own id, but when they enter the database, EF Core wants to assign a new id, due to the identity property. I don't need to change the id's, the data must be saved in the database as it comes from the API, so that later I can consult them. Here's the API link from where I'm getting the data: https://api.spaceflightnewsapi.net/v3/documentation
Maybe your list contains duplicates. EF does not allow to track entites with same key. If you have that error, try