开发者

Simple Code-First Entity Sample Not Saving

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())
{
   开发者_如何学Go 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'.;


You have a typo(?) - this:

    public DbSet<SingleEmail> SingleEmail{get;set;}

should be (plural)

    public DbSet<SingleEmail> SingleEmails{get;set;}

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 for SingleEmails. 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?


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'.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜