我有我在asp.net mvc教程的幫助下創建的以下代碼。 這些在我稱爲Model的不同類庫中。 我使用名爲HRContext的連接字符串在類庫中創建了一個app.config。 同樣在webproject上,我創建了相同的連接字符串。種子不適用EF 4.1
當我運行項目時,我把斷點和Seed方法從不執行,但OnModelCreating正在執行。
我收到了一個異常,表示dbo.Position不存在於視圖中。
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Position'.
Line 21: var positions = unitOfWork.PositionRepository.Find(p => p.PositionID != null);
Line 22:
Line 23: return View(positions.ToList());
Line 24: }
public class HRContextInitializer : DropCreateDatabaseAlways<HRContext>
{
protected override void Seed(HRContext context)
{
Position netdeveloper = new Position() { name = ".net developer", yearsExperienceRequired = 5 };
Position javadeveloper = new Position() { name = "java developer", yearsExperienceRequired = 5 };
byte[] johnImage = File.ReadAllBytes(@"\Content\Photos\1.jpg");
byte[] luisImage = File.ReadAllBytes(@"\Content\Photos\2.jpg");
Applicant luis = new Applicant()
{
name = "Luis",
skypeuser = "le.valencia",
telephone = "0491732825",
photo = luisImage
};
Applicant john = new Applicant()
{
name = "John",
skypeuser = "jo.valencia",
telephone = "3435343543",
photo = johnImage
};
ApplicantPosition appicantposition = new ApplicantPosition()
{
Applicant = luis,
Position = netdeveloper,
appliedDate = DateTime.Today,
Status = Status.Applied
};
ApplicantPosition appicantposition2 = new ApplicantPosition()
{
Applicant = john,
Position = javadeveloper,
appliedDate = DateTime.Today,
Status = Status.Applied
};
context.Positions.Add(netdeveloper);
context.Positions.Add(javadeveloper);
context.Applicants.Add(luis);
context.Applicants.Add(john);
context.ApplicantsPositions.Add(appicantposition);
context.SaveChanges();
}
}
public class HRContext : DbContext
{
public DbSet<Position> Positions { get; set; }
public DbSet<Applicant> Applicants { get; set; }
public DbSet<ApplicantPosition> ApplicantsPositions { get; set; }
public DbSet<ApplicationPositionHistory> ApplicationsPositionHistory { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Position>().ToTable("Position");
modelBuilder.Entity<Applicant>().ToTable("Applicant");
modelBuilder.Entity<ApplicantPosition>().ToTable("ApplicantPosition");
modelBuilder.Entity<ApplicationPositionHistory>().ToTable("ApplicationsPositionHistory");
modelBuilder.Entity<Position>().Property(c => c.name).IsRequired();
modelBuilder.Entity<Applicant>().Property(c => c.name).IsRequired();
modelBuilder.Entity<ApplicantPosition>().Property(c => c.appliedDate).IsRequired();
base.OnModelCreating(modelBuilder);
}
}