简体   繁体   English

C#关系数据库

[英]C# relational database

I have a relational table, where the connection is between users and notes.我有一个关系表,其中连接的是用户和笔记。 My problem我的问题

  1. _result.Entity.Id returns -2147482647 _result.Entity.Id返回 -2147482647

  2. I use Email as the key, but when creating more than one note there is an error stating that I already have such Email in the database, I would like to hear a solution to this problem.我使用电子邮件作为键,但是在创建多个便笺时出现错误,指出我在数据库中已经有这样的电子邮件,我想听听这个问题的解决方案。

  3. My task is to match the Id notes in the two tables, but in the communication table id equals (see 1)我的任务是匹配两个表中的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; }
}

I will be very grateful for any help我将非常感谢任何帮助

Your key is database-generated so you will have to give the db a chance to do just that:您的密钥是数据库生成的,因此您必须让数据库有机会做到这一点:

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};

And then you still have to SaveChanges a second time.然后你仍然需要第二次 SaveChanges。 Look into Navigation properties for a better way.查看导航属性以获得更好的方法。

With only the UserEmail as key in UserToDo, every user (email) can have only 1 ToDO item in your database.只有 UserEmail 作为 UserToDo 中的键,每个用户(电子邮件)在您的数据库中只能有 1 个 ToDO 项目。

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

change this model to:将此模型更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM