2

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!

DuongSon
  • 21
  • 2
  • What is `while (DataAccess.Queries.CheckExistInGroup(newGroup.MaNhom) == true);` there for? – Zack Tarr Mar 07 '20 at 03:42
  • might be unrelated, but it seems you are trying to force a random value onto a primary key column, you could simplify the process by making your `[int] [primary key] MaNhom` to also `AUTO_INCREMENT` – timur Mar 07 '20 at 08:12
  • @Zack Tarr: The condition means that while this value of newGroup.MaNhom (MaNhom is id of group) already existed in table 'groups', we still random it. – DuongSon Mar 08 '20 at 01:47

1 Answers1

1

actually, after posting my comment I had a bit of a brainwave, which might end up answering your question. This is a theory:

you mentioned your table is defined as follows:

CREATE TABLE groups(
   MaNhom INT primary key,
   TenNhom CHAR(100)
);

that yields an Entity, correctly decorated with [Key] attribute:

public partial class group
    {
        [Key]
        public int MaNhom { get; set; }
        public string TenNhom { get; set; }
    }
}

what I suspect happens when you call EF's .SaveChanges() is it completely ignores the value id MaNhom assuming that the DB will take care of it. in MySQL however, the PK will not auto-increment unless you tell it to. Which is where you need to either:

1. update table:

CREATE TABLE groups(
   MaNhom INT AUTO_INCREMENT PRIMARY KEY,
   TenNhom CHAR(100)
);

2. update model:

this SO answer provides some guidance:

public partial class group
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int MaNhom { get; set; }
        public string TenNhom { get; set; }
    }
}
timur
  • 14,239
  • 2
  • 11
  • 32
  • Thank for your answer but I have several question. I think auto_increment means that the value of this field will increase automatically. In my case, I don't need value of the field 'MaNhom' increases automatically when I add a new record. I just want to insert a new record with optional value of field MaNhom. (You can ignore my commands regarding randomming and assume that I am setting the value of newGroup.MaNhom to an optional integer). Even if I want to do that, do I still need set MaNhom as auto_increment? Thank you! – DuongSon Mar 08 '20 at 01:42
  • 1
    It's really hard to give you advice without knowing your data model/requirements. You can technically have a table with no auto increment PK (or even no PK, I'm not 100% sure how mySQL handles this). You might try remove [Key] from your schema and roll this way, but be aware that the performance of selects to this table will suffer unless you have supporting indexes in place. – timur Mar 08 '20 at 03:10
  • Thanks for your answer. I recently found a way to solve it (but it seems stupid). I set type of 'MaNhom' as string. In C# code, after randomming the value of 'MaNhom' I covert it to string and add into table groups. It works fine. Can't have a table without key, it won't work. – DuongSon Mar 14 '20 at 01:37