[英]Trying to Query a SQL Server from ASP.net MVC 4 using C#
I am trying to use a query to find the last ID (entry) in the table called ContributorUser in the database FPTContributorUsers and then add in a new entry thus assigning it the next available ID. 我正在尝试使用查询在数据库FPTContributorUsers中查找名为ContributorUser的表中的最后一个ID(条目),然后添加一个新条目,从而为其分配下一个可用ID。
the below code allows me to add data to the table in the database however when I run it the ID (new entry to the table) shows as 0 and not 4. because I currently have three entries in my table 下面的代码允许我将数据添加到数据库中的表中,但是当我运行它时,ID(表的新条目)显示为0而不是4.因为我目前在表中有三个条目
[HttpPost]
public ActionResult AddContributor(ContributorUsers AddCont)
{
if (AddCont.UserID == null)
{
throw new HttpException(404, "Please enter a valid RacfId");
}
else
{
FPTContributorUsers NewUser = new FPTContributorUsers();
NewUser.UserID = AddCont.UserID;
NewUser.ID = AddCont.ID;
db.ContributorUsers.Add(NewUser);
db.SaveChanges();
return RedirectToAction("index");
}
}
Have you thought about just making that the primary key and having it auto increment so you don't need to determine what it is yourself? 您是否考虑过将其作为主键并使其自动增加,这样您就不需要确定它本身是什么? That's usually the best way to go about handling actual ID's in my experience.
根据我的经验,这通常是处理实际ID的最佳方式。
To do this in SQL Server follow these steps 要在SQL Server中执行此操作,请执行以下步骤
To do this in MySQL follow these steps 要在MySQL中执行此操作,请执行以下步骤
As a note, if you do this you will need to update your EF model. 请注意,如果您这样做,则需要更新EF模型。
The other way to do it if you can't edit the database is to use MAX() for that column which will return the highest ID value, then just add one to it, no EF model updating required. 如果你不能编辑数据库,另一种方法就是对该列使用MAX(),它将返回最高的ID值,然后只需添加一个,不需要更新EF模型。
Try removing the "NewUser.ID = AddCont.ID" line and wait to get the NewUser.ID until after "db.SaveChanges()" 尝试删除“NewUser.ID = AddCont.ID”行并等待获取NewUser.ID,直到“db.SaveChanges()”之后
else
{
FPTContributorUsers NewUser = new FPTContributorUsers();
NewUser.UserID = AddCont.UserID;
db.ContributorUsers.Add(NewUser);
db.SaveChanges();
return RedirectToAction("index");
}
If the NewUser.ID property is an Identity Field in the database, it will not get populated until after the record is created during the SaveChanges() transaction commit. 如果NewUser.ID属性是数据库中的标识字段,则在SaveChanges()事务提交期间创建记录之后才会填充它。
在调用NewUser.ID之前尝试Reload()在SaveChanges()之后的数据库上下文,以便上下文是最新的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.