插入新记录时,mysql实体框架6“字段是必需的”错误

时间:2014-01-09 14:23:03

标签: mysql entity-framework insert

当我尝试将记录插入表格时,我收到错误。

请注意,我不是在使用MySQL实体框架。

模型:

public class products {
    public string ArtNo { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

图:

<EntityType Name="products">
    <Key>
        <PropertyRef Name="ArtNo" />
    </Key>
    <Property Name="ArtNo" Type="varchar" Nullable="false" />
    <Property Name="Title" Type="varchar" Nullable="false" />
    <Property Name="Description" Type="longtext" Nullable="false" />
</EntityType>

代码:

        using(mydbEntities d = new mydbEntities()) {
            products newProduct = new products();
            newProduct.ArtNo = "x001";

            d.products.Add(newProduct);
            try {
                d.SaveChanges();
            } catch(System.Data.Entity.Validation.DbEntityValidationException ex) {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                foreach(var failure in ex.EntityValidationErrors) {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach(var error in failure.ValidationErrors) {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new System.Data.Entity.Validation.DbEntityValidationException(
                        "Entity Validation Failed - errors follow:\n" +
                        sb.ToString(), ex
                ); // Add the original exception as the innerException
            }
        }

错误:

{"Entity Validation Failed - errors follow:
myMVC.DBModel.products failed validation
- Title : The Title field is required.
- Description : The Description field is required.
"}

当我尝试使用mysqlcommand时,我没有收到任何错误:

MySqlCommand c = new MySqlCommand(con);
c.CommandText = "insert into products (artno) values ('x001')";
c.ExecuteNonQuery();

修改

我认为实体框架会生成如下的SQL语句:

insert into products (ArtNo,Title,Description) values ('x001',NULL,NULL)

但是,Title和Description字段是“不可为空的”;然后它会抛出一个错误。 (默认值为空字符串。)

我没有设置Title和Description属性,所以我希望SQL语句如下:

insert into products (ArtNo) values ('x001')

1 个答案:

答案 0 :(得分:0)

这是因为在您的EntityType Name="products"声明中,您提及的两个字段都标记为nullable="false"。因此EF返回该错误。当您运行mysqlcommand时,呼叫不会通过EF层。