How to save Product Order details with User Id?


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

 20525361_792910367548746_153501979402843294


Asked by:- zeeshanAslam
1
: 5807 At:- 8/2/2017 7:31:07 AM
C# MVC sql-server entity-framework







2 Answers
profileImage Answered by:- vikas_jk

@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

1
At:- 8/2/2017 7:54:30 AM


profileImage Answered by:- zeeshanAslam

 

 

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.

0
At:- 8/2/2017 9:11:22 AM
as you are referring student.User_Id.Id, which is wrong, you nee to save Id of int type in Student table. So create a column of type int in Student table, save UserId in that table, suppose column name is UserId, code should be. Student.UserId=UserId. Right now you are referring User Object from Student object, which is not correct 0
By : vikas_jk - at :- 8/2/2017 10:19:00 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use