实体框架代码第一数据库不更新

时间:2012-10-07 13:07:56

标签: c# winforms entity-framework ef-code-first sql-server-ce

前一天,我开始在简单的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; }
}

然后我使用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);
}

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

我通过代码添加了一行:

Saves s = new Saves();
s.Player = "TestName";
s.Age = 5110;
s.Money = 200;
db.SavesSet.Add(s);
db.SaveChanges();

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; }

我的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>

1 个答案:

答案 0 :(得分:1)

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

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

因此,当你保存东西时,它确实会保存到错误的数据库。

相关问题