I'm trying to build a simple ASP.NET MVC website but I encountered some problem. I can't add a new record with integer value into database by using linq command. I have a table called 'groups' in database. It's following: groups([int] [primary key] MaNhom, [char(100)] TenNhom). Explain: MaNhom is GroupID, TenNhom is GroupName. (Sorry for this convenience when I name these field by Vietnamese.). I add an ADO.NET Entity Data Model and a class called 'group.cs' is generated.
public partial class group
{
[Key]
public int MaNhom { get; set; }
public string TenNhom { get; set; }
}
}
I also create a class in Models folder of my web project called Group.
public class Group
{
[Key]
public int MaNhom { get; set; }
public string TenNhom { get; set; }
}
I created a view called CreateManageGroup.cshtml. The content of it is following:
@{
ViewBag.Title = "CreateManageGroup";
}
<h2>Create A Group</h2>
<form action="/account/CreateManageGroup" method="post">
<label for="TenNhom"> Name of Group </label>
<input type="text" name="TenNhom" id="inputGroupName">
<input type="submit" value="Create">
</form>
When I submit it, value of TenNhom will be sent to and saved in parameter 'group' of method CreateManageGroup(Group group) in AccountController.
[HttpPost]
public ActionResult CreateManageGroup(Group group)
{
if (ModelState.IsValid == true)
{
var newGroup = new DataAccess.group();
newGroup.TenNhom = group.TenNhom;
var randomObject = new Random();
do
{
newGroup.MaNhom = randomObject.Next(1, 9999);
}
while (DataAccess.Queries.CheckExistInGroup(newGroup.MaNhom) == true);
DataAccess.Queries.ExcuteInsertIntoGroup(newGroup);
return RedirectToAction("SignUp");
}
else
{
return View();
}
}
I checked and I know newGroup.MaNhom is set a value different zero after randomming, such as 3309. But after calling method ExcuteInsertIntoGroup(newGroup), value of MaNhom of table groups in database is 0. The content of ExcuteInsertIntoGroup():
namespace DataAccess
{
public class Queries
{
public static void ExcuteInsertIntoGroup(group record)
{
phep_toanDatabase.groups.Add(record);
phep_toanDatabase.SaveChanges();
}
}
}
Note: phep_toanDatabase is variable declared in class Queries of class library DataAccess:
public static phep_toanEntities phep_toanDatabase;
static DataAccess()
{
phep_toanDatabase = new phep_toanEntities();
}
My question is: Why after excuting linq command, value of MaNhom displayed in table groups as 0 although newGroup.MaNhom is set to a value different 0 before? Thank you!