C# 关系型数据库

标签 c# sql asp.net-core entity-framework-core

我有一个关系表,其中连接在用户和注释之间。我的问题

  1. _result.Entity.Id 返回 -2147482647

  2. 我使用Email作为key,但是当创建多个note时出现错误提示我已经在数据库中有这样的Email,我想听听解决这个问题的方法。

  3. 我的任务是匹配两个表中的id注释,但是在通信表中id等于(见1)

[HttpPost]
public async Task<IActionResult> Create(AddToDoViewModel model)
{
    if (ModelState.IsValid)
    {
        ToDo toDo = new ToDo {Name = model.Tittle, Body = model.Body };
        var _result = await db.ToDos.AddAsync(toDo);

        UserToDo userToDo = new UserToDo { ToDoId = _result.Entity.Id, UserEmail = User.Identity.Name};
        var result = await db.UserToDos.AddAsync(userToDo);

        db.SaveChanges();

        return Redirect("/Profile");
    }

    return View(model);
}

public class ToDo
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Body { get; set; }
}

public class UserToDo
{
    [Key]
    public string UserEmail { get; set; }
    public int ToDoId { get; set; }
}

如果有任何帮助,我将不胜感激

最佳答案

您的 key 是由数据库生成的,因此您必须让数据库有机会这样做:

var _result = await db.ToDos.AddAsync(toDo);
db.SaveChanges(); // this generates and fetches the new key
UserToDo userToDo = new UserToDo { ToDoId = _result.Entity.Id, UserEmail = User.Identity.Name};

然后您仍然需要第二次 SaveChanges。查看导航属性以获得更好的方法。

在 UserToDo 中只有 UserEmail 作为键,每个用户(电子邮件)在您的数据库中只能有 1 个 ToDO 项目。

public class UserToDo
{
    [Key]
    public string UserEmail { get; set; }
    [Key] // add this to create a composite key
    public int ToDoId { get; set; }
}

关于C# 关系型数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55888309/

相关文章:

c# - ASP.NET MVC 5 中的 DateCreated 和 DateModified

SQL:是否有一种巧妙的方法可以在不使用内部查询或聚合函数的情况下在数据透视列中显示文本数据?

sql - 如何在 Oracle 数据库查询中忽略区分大小写

asp.net - 如何在 ASP.Net Core 中设置全局化文化?

azure - SignalR核心: is ARR affinity needed when web sockets are enabled and the Azure app service is scaled out to multiple instances?

c# - Azure blob 存储 - 分块文件上传 - 跨回发缓存数据

c# - 调用子 <frame> 中指定的 JavaScript 函数

c# - Razor 表单在页面上显示不需要的文本

mysql - SQLYog 为 MySQL 设置变量返回 null

c# - 是否可以创建通用 API GET 操作?