Tôi có mô hình Khung thực thể được tạo tự động. Nó được tạo ra bằng cách sử dụng một phương pháp tiếp cận cơ sở dữ liệu đầu tiên. Cột mid_initial
có ràng buộc xác định cơ sở dữ liệu giới hạn cột ở độ dài tối đa là 3 ký tự.Cơ sở dữ liệu Xác thực lần đầu
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Agency.DataAccess.RegistrationModel
{
using System;
using System.Collections.Generic;
public partial class Registrant
{
public Registrant()
{
}
public int id { get; set; }
public string fname { get; set; }
public string mid_initial { get; set; }
public string lname { get; set; }
}
}
Khi tôi cố gắng và tạo ra một mô hình với một mid_initial
lớn hơn 3 ký tự, một trạng thái không hợp lệ, ModelState.IsValid
đang trở thành sự thật. Bởi vì điều này db.SaveChanges
sau đó được gọi, sau đó tăng DbEntityValidationException
.
[HttpPost]
public ActionResult Create(Registrant registrant)
{
try
{
if (ModelState.IsValid)
{
Debug.WriteLine("Entity was valid.");
db.Registrants.Add(registrant);
db.SaveChanges();
return RedirectToAction("Index");
}
return View("Create", registrant);
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
return View(registrant);
}
}
Tại sao phương pháp ModelState.IsValid
trả về đúng? Có vẻ như mô hình của tôi không biết về giới hạn độ dài tối đa. Làm thế nào để làm cho nó nhận thức?
Đóng ... Nhưng, như tôi hiểu, nó sẽ không hoạt động. Trình biên dịch sẽ nói: "Lỗi 2 Kiểu 'Người đăng ký' đã chứa định nghĩa cho 'mid_initial' ...). Cần đánh dấu lớp' Người đăng ký' bằng thuộc tính 'MetadataType' và tạo một lớp khác để xác nhận hợp lệ http: // stackoverflow. com/questions/25722866/ef5-db-first-generated-models-and-custom-validation/25741213 # 25741213 –