来自URL的数据(JSON)已经具有ID。如何使用实体框架将数据添加到数据库中

发布于 2025-02-03 03:51:02 字数 1571 浏览 4 评论 0原文

我想从URL(JSON)中将数据添加或更新数据,但是此数据已经具有ID值。

JSON文件

[
    {
        "id": 0,
        "first_name": "Tony",
        "last_name": "Stark",
        "date": "2008-07-06"
    },
    {
        "id": 1,
        "first_name": "David",
        "last_name": "Guetta",
        "date": "2008-08-05"
    },
...

模型

public class Person
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string FirstName{ get; set; }
    [Required]
    public string LastName{ get; set; }
    [Required]
    public DateTime Date { get; set; }
}

控制器索引方法:

public async Task<IActionResult> Index()
{
    string json;

    using (HttpClient client = new HttpClient())
    {
       json = client.GetStringAsync(Url).Result;
    }

    var people = JsonConvert.DeserializeObject<List<Person>>(json);

    if (people is not null)
    {
        await _context.AddRangeAsync(people);
        await _context.SaveChangesAsync();
    }

    return _context.People != null ?
                View(await _context.People.ToListAsync()) :
                Problem("Entity set 'ApplicationDbContext.People'  is null.");
}

加载此页面后,出现错误,键和ID问题。我知道问题是JSON数据具有id值,但我不知道如何避免。有任何解决方案吗?如何将ID值保留在JSON中并告诉数据库“请不要生成ID值,请从我的转换JSON文件中获取ID值”

invalidoperationException:无法跟踪实体类型的实例,因为已经跟踪具有相同密钥值的另一个实例。连接现有实体时,请确保仅附有一个具有给定键值的实体实例。
考虑使用“ dbcontextoptionsbuilder.senablesenablesitivedAtalogging”以查看相互矛盾的钥匙值。

多谢

I want to add or update data in database from url (json), but this data already has the id value.

JSON file

[
    {
        "id": 0,
        "first_name": "Tony",
        "last_name": "Stark",
        "date": "2008-07-06"
    },
    {
        "id": 1,
        "first_name": "David",
        "last_name": "Guetta",
        "date": "2008-08-05"
    },
...

Model

public class Person
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string FirstName{ get; set; }
    [Required]
    public string LastName{ get; set; }
    [Required]
    public DateTime Date { get; set; }
}

Controller Index method:

public async Task<IActionResult> Index()
{
    string json;

    using (HttpClient client = new HttpClient())
    {
       json = client.GetStringAsync(Url).Result;
    }

    var people = JsonConvert.DeserializeObject<List<Person>>(json);

    if (people is not null)
    {
        await _context.AddRangeAsync(people);
        await _context.SaveChangesAsync();
    }

    return _context.People != null ?
                View(await _context.People.ToListAsync()) :
                Problem("Entity set 'ApplicationDbContext.People'  is null.");
}

After loading this page, the error shows up, problem with the key and id. I know that the problem is that json data has the id values, but I don't know how to avoid that. Is there any solution. How to keep id values from json and tell the database "please, don't generate the id values, take the id values from my converted json file"

InvalidOperationException: The instance of entity type 'Person' 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.

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生生漫 2025-02-10 03:51:02

我终于找到了解决方案。它需要另一种数据注释。因此,SQL Server不会增加ID

[DatabaseGenerated(DatabaseGeneratedOption.None)]

模型

public class Person
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Required]
    public string? FirstName { get; set; }
    [Required]
    public string? LastName { get; set; }
    [Required]
    public DateTime Date { get; set; }
}

,然后将实际执行添加或更新数据的方法,因为如果表格已经填充了表,则首先会截断表。

public async Task<IActionResult> GetUpToDateData()
{
    string json;
    using (HttpClient client = new())
    {
        json = client.GetStringAsync(Url).Result;
    }

    var people = JsonConvert.DeserializeObject<List<Person>>(json);

    if (people is not null)
    {
        await _context.Database.ExecuteSqlRawAsync("TRUNCATE TABLE [People]");
        await _context.AddRangeAsync(people);
        await _context.SaveChangesAsync();
    }

    return RedirectToAction(nameof(Index));
}

I have finally found the solution. It has been required another data annotation. So the Sql server will not increment the Id

[DatabaseGenerated(DatabaseGeneratedOption.None)]

Model

public class Person
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [Required]
    public string? FirstName { get; set; }
    [Required]
    public string? LastName { get; set; }
    [Required]
    public DateTime Date { get; set; }
}

And then the method that actually do the add or update data, because if the table is already populated it truncate the table first.

public async Task<IActionResult> GetUpToDateData()
{
    string json;
    using (HttpClient client = new())
    {
        json = client.GetStringAsync(Url).Result;
    }

    var people = JsonConvert.DeserializeObject<List<Person>>(json);

    if (people is not null)
    {
        await _context.Database.ExecuteSqlRawAsync("TRUNCATE TABLE [People]");
        await _context.AddRangeAsync(people);
        await _context.SaveChangesAsync();
    }

    return RedirectToAction(nameof(Index));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文