I have a user table & I want whenever a user orders a product, its order should be saved in order table with user primary key, so what relationship I have to add in user and order table. please let me know
Suppose, this is my ActionMethod
public ActionResult Create( Student student)
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
Database Relationship image
@Zeeshan, thanks for asking a question here.
Firstly, you need to Create relation one-to-many relation, between Order table and User Table.
For example, there must be a Primary key in Users table which is named as "Id" (as per above image), in Student(or Order) table, there must a column named as "UserId", this column should be foreign key and "Id" of User table must be primary key.
Now in the C# code, you need to fetch logged in user id, to save it in the database, looking at your above code, you should do some changes and correct code should be
public ActionResult Create( Student student)
{
if (ModelState.IsValid)
{
//Get Currently Logged in user id, don't forget to include using Microsoft.AspNet.Identity;
var UserId= User.Identity.GetUserId();
//to save UserId in model
student.User_ID_id=UserId;
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
That's it, it should work, thanks, upvote my answer if it works for you
Exception is showing ... i don't know how to fix it.
this is my model student class code that i wrote in student model to make it forien key in student table .
public virtual User User_ID { get; set; }
User is user model class.
User Class.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly