我試圖在總是使用DBfirst之後首次使用代碼,但由於某種原因,當我運行我的項目時,它不會創建我的表格,而且我很頭疼我失蹤即使閱讀了很多stackoverflow的帖子。未創建實體框架表(代碼優先)
我有以下代碼:
Class.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EdulySoft.Models
{
public partial class Class
{
public int Id { get; set; }
public int ClassRoomId { get; set; }
public string ClassName { get; set; }
public int MaxStudents { get; set; }
public virtual Classroom classrooms { get; set; }
}
}
classroom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EdulySoft.Models
{
public partial class Classroom
{
public Classroom()
{
this.classes = new HashSet<Class>();
}
public int Id { get; set; }
public string ClassRoomName { get; set; }
public ICollection<Class> classes { get; set; }
}
}
SchoolContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EdulySoft.Models
{
public class schoolContext : DbContext
{
public schoolContext() : base()
{
}
public DbSet<Class> Classes { get; set; }
public DbSet<Classroom> Classrooms { get; set; }
}
}
的Program.cs
using EdulySoft.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EdulySoft
{
class Program
{
static void Main(string[] args)
{
using (var ctx = new schoolContext())
{
Class stud = new Class() { Id = 1, ClassName = "Loquat", MaxStudents = 12, ClassRoomId = 1 };
ctx.Classes.Add(stud);
ctx.SaveChanges();
}
}
}
}
的App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="EdulySoft.Properties.Settings.schoolContext"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Eduly;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
我用了一個空的控制檯應用程序開始。任何幫助都感激不盡。歡呼!
您是否創建了遷移並更新了數據庫? – mboldt
我還沒有創建遷移,是否需要創建數據庫? –
是的。更改後,您需要轉到程序包管理器控制檯並鍵入「添加遷移您的遷移名稱」。您將看到已創建遷移的代碼,然後您可以在控制檯中鍵入「update-database」。這應該更新你的數據庫。但是請確保您在控制檯的「默認項目」下選擇了EF-Project。 – mboldt