当我尝试向表中插入记录时出现错误。
请注意,我正在使用 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/