在mvc中插入2个表 [英] Inserting into 2 tables in mvc

查看:67
本文介绍了在mvc中插入2个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有2个表,名为用户表和工时表

用户表

UserId --->主键

名称

描述





WorkHour表


WorkHourId

UserId

时间







在控制器中保存数据时,userId应插入两个表中。我的问题是插入用户表是否正确创建。我的问题是在workhour表中,userid正在添加一个单独的列,workhourid随着时间的推移正在添加为一个单独的列。



我将添加我的代码供您参考。

I have 2 tables in database named as user table and work hour table
User Table
UserId ---> Primary key
Name
Description


WorkHour table

WorkHourId
UserId
Time



In controller while saving a data userId should be inserted in both the tables.My problem is while inserting user table is created properly. My problem is in workhour table userid is adding in a separate column and workhourid with time is adding as a separate column .

I will add my code for your reference.

[HttpPost]
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(tblUser tbluser,  FormCollection coll, WorkingHour hour)
{
    WorkingHour hr = new WorkingHour();
    if (ModelState.IsValid)
    {
        hr.UserId2 = tbluser.UserID;
   
        EmailManager.SendConfirmationEmailName(tbluser.EmailID,tbluser.FirstName);
        @Response.Redirect("~/Login/BULogin");
                    
        db.tblUsers.Add(tbluser);
        db.WorkingHours.Add(hr);
        db.SaveChanges();
    }

    ViewBag.AddressId = new SelectList(db.tblAddresses, "AddressID", "Address1", tbluser.AddressId);
    ViewBag.BusinessCategoryId = new SelectList(db.tblBusinessCategories, "BusinessID", "BusinessName", tbluser.BusinessCategoryId);
    ViewBag.UserTypeId = new SelectList(db.tblUserTypes, "UserTypeID", "UserType", tbluser.UserTypeId);
    //    ViewBag.WorkHourId = new SelectList(db.WorkingHours, "WorkHourId");
    //(int)Session["UserID"];
    return View(tbluser);
}



请帮我解决。在此先感谢


Please help me to fix it . Thanks in advance

推荐答案

不确定我是否正确理解了您的问题,但是当您向User表添加新行时,您要么在代码中决定用户ID(不好)方式)或让数据库为您生成一个唯一的ID(好方法)。无论哪种方式,您都可以获得新插入用户的用户ID,并在添加到workhour表时使用相同的ID。



这当然意味着您必须在通话之间存储用户ID才能在以后使用它。



为了在数据库中生成用户ID,我建议使用 NEWID(Transact-SQL) [ ^ ]
Not sure if I understood your question correctly, but when you add a new row to the User table you either decide the userid in your code (bad way) or let the database generate a unique id for you (good way). Either way you get the user id for a newly inserted user and use the same id when adding to workhour table.

This of course means that you have to store the user id between the calls in order to use it later.

For user ID generation in the database I'd suggest using NEWID (Transact-SQL)[^]


这篇关于在mvc中插入2个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆