C# relational database

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

Question

I have a relational table, where the connection is between users and notes. My problem

  1. _result.Entity.Id returns -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)

[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

1
2
4/28/2019 8:51:03 AM

Accepted Answer

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. 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.

public class UserToDo
{
    [Key]
    public string UserEmail { get; set; }
    [Key] // add this to create a composite key
    public int ToDoId { get; set; }
}
1
4/28/2019 9:30:26 AM

Popular Answer

change this model to:

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow