mysql Entity Framework 6插入新记录时出现 "field is required"错误

标签 mysql entity-framework insert

当我尝试向表中插入记录时出现错误。

请注意,我正在使用 MySQL Entity Framework 。

型号:

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();

编辑:

我认为 Entity Framework 生成这样的SQL语句:

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

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

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

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

最佳答案

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

关于mysql Entity Framework 6插入新记录时出现 "field is required"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21022819/

相关文章:

mysql - 使用多个线程执行多个 sequelize 查询

MySQL 5.5 : Efficient way to copy the same user information with different IDs

php - 在数据库 MYSQL 中插入数据,数据混合

javascript - 动态添加脚本标签到页面

MySQL插入查询错误

php - Codeigniter Cpanel 上数据库连接错误

MYSQL从两个不同的表中选择数据并且没有公共(public)变量名

c# - 如何实现 DateTime 实体属性以始终设置 DateTime.Now

linq - 如何使用多个 .Select() 简化 LINQ 查询以返回 IQueryable(int)

entity-framework - Entity Framework 6 延迟加载和查询导航属性