I have a relational table, where the connection is between users and notes. My problem
_result.Entity.Id
returns -2147482647
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.
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
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; }
}
change this model to:
public class UserToDo
{
[Key]
public string UserEmail { get; set; }
public int ToDoId { get; set; }
public ToDo ToDo { get; set; }
}