0
我在嘗試向表中插入記錄時出現錯誤。mysql實體框架6「插入新記錄時需要輸入」錯誤
請不要指出我正在使用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)
但是,標題和說明字段「不可爲空」;那麼它會拋出一個錯誤。 (默認值是空字符串。)
我沒有設置標題和描述特性,所以我希望SQL語句是這樣的:
insert into products (ArtNo) values ('x001')
你可以顯示你的模型的屬性? –
編輯;我添加了模型。它沒有attr –
您的產品類是部分的。其他部分有屬性嗎?是否已根據需要使用FluentAPI指定了該字段? – Colin