EntityFramework CodeFirst数据库不会更新

aha*_*mas 5 c# entity-framework sql-server-ce winforms ef-code-first

一天前,我开始在简单的Windows窗体项目(C#)中使用Entity Framework CodeFirst.我创建了两个模型:

[Table("SavesSet")]
public partial class Saves
{
    public Saves()
    {
        this.SkillsSet = new HashSet<Skills>();
    }

    [Key]
    public int SaveID { get; set; }

    public string Player { get; set; }
    public int Age { get; set; }
    public int Money { get; set; }

    public virtual ICollection<Skills> SkillsSet { get; set; }
}

[Table("SkillsSet")]
public partial class Skills
{
    [Key]
    public int SkillID { get; set; }

    public string Name { get; set; }
    public int Value { get; set; }
    public int SavesSaveID { get; set; }

    public virtual Saves SavesSet { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后我使用Visual Studio Database Explorer(使用SqlServerCe 3.5的本地数据库)在我的数据库中添加了一行:

SaveID = 1

Player ="TEST"

年龄= 1

钱= 1

我还用ListView创建了表单并编写了一些代码:

private SavesContext db = new SavesContext();
foreach (Saves s in db.SavesSet.ToList())
{
    ListViewItem l = new ListViewItem();
    l.Name = s.SaveID.ToString();
    l.Text = s.Player;
    ListViewSaves.Items.Add(l);
}
Run Code Online (Sandbox Code Playgroud)

但是当我启动程序调试时,ListView是空的.我设置断点,查看局部变量并看到SavesSet计数为0.

我通过代码添加了一行:

Saves s = new Saves();
s.Player = "TestName";
s.Age = 5110;
s.Money = 200;
db.SavesSet.Add(s);
db.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

并且ListView显示了这一个.但在我的数据库中没有任何东西(它的大小没有变化).我重新启动Visual Studio - 我的麻烦仍然是实际的:ListView显示项目,但数据库是空的.我在App.Config和VS Database Explorer中检查了ConnectionString - 它们是相同的.

所以,我的问题是:我如何探索我的真实数据库以及它存储在哪里?

更新.

我的DbContext:

    public SavesContext()
        : base("Saves")
    {
    }

    public DbSet<Saves> SavesSet { get; set; }
    public DbSet<Skills> SkillsSet { get; set; }
Run Code Online (Sandbox Code Playgroud)

我的App.Config:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <configSections>
        </configSections>
        <connectionStrings>
            <add name="TextSim.Properties.Settings.Saves" connectionString="Data          
            Source=C:\Documents and Settings\My\My Documents\visual studio       
            2010\Projects\TextSim\TextSim\Saves.sdf"
            providerName="System.Data.SqlServerCe.3.5" />
        </connectionStrings>
     </configuration>
Run Code Online (Sandbox Code Playgroud)

Eri*_*sch 1

实体框架使用称为“约定优于配置”的方法,这意味着如果您不为某些事物提供值,它将使用默认值。

如果您不指定连接字符串,它将使用从 EF 的命名空间和 DbContext 名称派生的默认连接字符串。如果是这种情况,那么它将使用默认系统创建一个新的(空白)数据库,而不是使用您在 Web.Config 中配置的数据库。

因此,当您保存内容时,它确实会保存到错误的数据库中。