Visual Studio 2010, C# 4.0 및 Entity Framework 5.0을 사용하고 있습니다.Entity Framework 5.0, 코드 우선, 유창한 API 및 데이터베이스 시드
내 (간체) 모델은 다음과 같습니다
public class DataContext : DbContext
{
public DbSet<Case> Cases { get; set; }
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Case>()
.HasKey(m => m.CaseID)
.Property(m => m.CaseID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Case>()
.HasRequired(m => m.User)
.WithRequiredPrincipal(m => m.Case);
}
}
그리고 내가 함께 데이터베이스를 파종하고 있습니다 :
public class Case
{
public int CaseID { get; set; }
public int CaseStatusID { get; set; }
public DateTime DateOfNotification { get; set; }
public User User { get; set; }
public Case()
{
}
}
public class User
{
public int UserID {get;set;}
public string Name { get; set; }
public Case Case { get; set; }
public User()
{
}
}
데이터 컨텍스트가없는 씨앗을
protected override void Seed(DataContext context)
{
Case Case = new Case();
Case.CaseStatusID = 1;
Case.DateOfNotification = DateTime.Today;
Case.User = new User();
Case.User.UserID = Case.CaseID;
Case.User.UsersFamilyNameEnc = "Smith";
Case.User.UsersGivenNameEnc = "Petra";
context.Cases.AddOrUpdate(Case);
context.SaveChanges();
}
사용하여 마이그레이션 데이터베이스가 오류없이 전개되고 데이터베이스를 수동으로 채울 수 있습니다.
User
클래스를 주석 처리하면 데이터베이스가 올바르게 시드됩니다.
인한 문제
은 곧 내가 user
관계를 추가하고 이주 명령을 실행으로이 오류
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
내가 도달 EntityValidationErrors 및 브레이크 포인트와하지를 볼 수 없습니다를 얻을.
문제는 관계에있는 것 같습니다. 나는 이것을 지정하는 다른 방법을 시도했지만 그 결과는 항상 동일하다. 에러 이해 -
답변
Getting exact error type in from DbValidationException 는 용액의 첫 번째 부분이다. 나는 다음 errorto에게 패키지 관리자 콘솔을 얻기 위해 시도로
catch (DbEntityValidationException dbEx)
{
StringBuilder sb = new StringBuilder();
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
sb.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
throw new Exception(sb.ToString());
}
(다른 두 답변의 amalgm)를 추가 할 필요가 있었다.
[NotMapped]
[Required(ErrorMessage = "The family name/surname is required")]
[Display(Name = "Family name/surname")]
public string UserName { get; set; }
은 내가 NotMapped
필드를 제외 것이라고 생각하지만 Required
는이 메소드를 오버라이드 (override) 할 것 같다
마지막으로, 나는 나의 '진짜'모델은 다음과 같은 포함 된 것을 발견했다. 일단 내가 이것에 대한 가치를 넣어 모든 일을 시작했다.
'EntityValidationErrors'를 보려면 다음을 확인하십시오. http://stackoverflow.com/questions/5345890/getting-exact-error-type-in-from-dbvalidationexception – lightbricko
감사합니다. 추적 출력이 나타나는 위치를 볼 수 없습니다. 그것은 디버그 창에 없습니다. 감사. –
항상 새로운 사용자를 만들고 있습니다. 그게 니가 원하는거야? – user1908061