【发布时间】:2012-10-07 13:07:55
【问题描述】:
一天前,我开始在简单的 Windows 窗体项目 (C#) 中使用实体框架 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 数据库资源管理器(使用 SqlServerCe 3.5 的本地数据库)在我的数据库中添加了一行:
保存ID = 1
播放器 =“测试”
年龄 = 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>
【问题讨论】:
-
断开它并重新连接(右键单击数据库)
-
感谢您的评论,但我已经尝试过很多次了。它不工作。
-
你能告诉我们你的连接字符串吗?
-
我尝试了两个 ConnectionStrings - 它们都不起作用:“Data Source=|DataDiretory|/Saves.sdf”和“Data Source=C:\Documents and Settings\My\My Documents\visual studio 2010\Projects\TextSim\TextSim\Saves.sdf".
-
我很惊讶它甚至可以工作,因为您的连接字符串的命名与您配置的不同。您的 dbcontext 应该是
base("name=TextSim.Properties.Settings.Saves")
标签: c# winforms entity-framework ef-code-first sql-server-ce