开发者

Insert Not Saving Using EF 4.1 Code First

I'm having an issue here that is blowing my mind. It's a very simple insert into a very simple table... something I've done a thousand times, but isn't working here for some reason.

Basically, I'm running a simple INSERT (via the repository pattern) and then saving the context changes. There are no errors, I can step through it just fine, but the record just isn't in the database.

In the interest of (hopefully) covering my butt against stupidity: I know I'm connected to the right database because it's fetching the seed data just fine (and there's only 1 connection string in my app). Also, I know the database isn't being rebuilt every time.

Here is the calling code:

var result = new Core.Models.Poll
{
    ElectionId = electionId,
    DatePublished = pubDate,
    DateCreated = DateTime.Now,
    NameEn = nameEn,
    NameFr = nameFr,
    Params = splitVals,
    Url = url,
    Slug = String.Empty
};    

Components.PollRepository.Insert(result);
Components.PollRepository.Save();

And here are the methods开发者_高级运维 in the repository:

public void Insert(Poll poll)
{
    Context.Polls.Add(poll);
}

public void Save()
{
    Context.SaveChanges();
}

At the Context.Polls.Add(poll); line, I inspect my object... when I manually run an insert statement in SSMS using values in the poll, the record gets created with no problem. When I run Context.Entry(poll) at the next line (the }), then I see that it's State is Added (as expected).

I'm running this using IIS Express on my local dev machine against SQLEXPRESS.

Oh, and here's key of the Poll class (I tried that DatabaseGenerated attribute with no luck):

[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

Any help, or even anything else to try, is greatly appreciated.


Check the declaration of the Context variable within the PollReppsitory. Also check the PollRepository property in Components. Make sure that the same instance is being returned each time.

You would see these results if the Context instance used to save the changes is not the one that was used for the insert.

You checked the state of the object within the Insert method. I would do the same in the Save method. If the entity is there and has a state of new then you can rule out my assumption that the insert and save are being performed on different contexts.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜