简单的代码优先实体示例未保存
为什么我保存的时候会出现这个错误?
模型:
public class SingleEmail
{
[Key]
public int MailID{get;set;}
public string ToAddress{get;set;}
public string Subject{get;set;}
public string Body{get;set;}
}
public class MyDBContext : DbContext
{
public DbSet<SingleEmail> SingleEmail{get;set;}
}
using (MyDBContext db = new MyDBContext())
{
SingleEmail m = new SingleEmail();
m.ToAddress = email.To[0].Address;
m.Subject = email.Subject;
m.Body = email.Body;
db.SingleEmail.Add(m);
db.SaveChanges();
}
{
更新时发生错误 条目。请参阅内部异常 详细信息。;
对象名称“dbo.SingleEmails”无效。;
Why is this error happening when I save?
Model:
public class SingleEmail
{
[Key]
public int MailID{get;set;}
public string ToAddress{get;set;}
public string Subject{get;set;}
public string Body{get;set;}
}
public class MyDBContext : DbContext
{
public DbSet<SingleEmail> SingleEmail{get;set;}
}
using (MyDBContext db = new MyDBContext())
{
SingleEmail m = new SingleEmail();
m.ToAddress = email.To[0].Address;
m.Subject = email.Subject;
m.Body = email.Body;
db.SingleEmail.Add(m);
db.SaveChanges();
}
{
An error occurred while updating the
entries. See the inner exception for
details.;Invalid object name 'dbo.SingleEmails'.;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有一个拼写错误(?) - 这:
应该是(复数)
否则您的
DbSet
与您的实体之一具有相同的名称,这可能是无意的,并且也不适合 EF 因为默认 EF 具有自动复数支持,因此它会寻找SingleEmails
。有解决方法,但在这种情况下,我只需重命名 Dbset - 这是有道理的。编辑:
尝试了您的示例模型,它在 EF 4.1 上运行良好 - 您使用的是哪个 EF 版本?
You have a typo(?) - this:
should be (plural)
Otherwise your
DbSet
has the same name as one of your entities, which is probably unintended and also doesn't go well with EF since by default EF has automatic pluralization support, hence its looking forSingleEmails
. There are workarounds for this but in this case I would just rename the Dbset - it makes sense.Edit:
Tried out your sample model and it works fine with EF 4.1 - what EF version are you using?
确保 App.config 文件中的连接字符串正确。我遇到了同样的错误,我跟踪它指向不包含新表的错误数据库。
就我而言,我的服务 DLL 项目的 App.config 使用新表设置为 Database1。实体框架在生成映射等时很好。
问题是我从控制台应用程序调用它,它自己的 App.config 指向错误的数据库。在运行时找不到表并且无法添加记录。我收到相同的错误
无效的对象名称“dbo.MyNewTableName”。
Make sure that your connection string is correct in your App.config file(s). I had the same same error and I tracked it down to pointing to the wrong database that didn't contain the new table.
In my case, my service DLL project's App.config was set to Database1 with the new table. The Entity Framework was fine when generating mappings etc.
The problem was that I was calling it from a console app with it's own App.config that was pointed to the wrong database. During run-time the table couldn't be found and the record couldn't be added. I got the same error
Invalid object name 'dbo.MyNewTableName'.