![](/img/trans.png)
[英]Inserting a record with specified primary key into MySQL via Entity Framework
[英]mysql entity framework 6 “field is required” error while inserting new record
尝试将记录插入表时出现错误。
请不要说我正在使用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();
编辑:
我认为实体框架会生成如下的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层。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.