Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6198803
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T04:04:41+00:00 2026-05-24T04:04:41+00:00

I’m using the latest and greatest Entity Framework Code First and I’m running into

  • 0

I’m using the latest and greatest Entity Framework Code First and I’m running into a scenario where I want one of my classes to use a string for the primary key. I had to manually add the key to the Create View (by default it treats it like an identity). However, when I try to create a new MyAccount, I get the error below. I’m using the MVC Scaffolder Repository pattern to build the MyAccountController. Your wisdom I seek with great appreciation.

Model:

public class MyAccount 
{
    [Key, Required, MaxLength(80), Display(Name = "User name")]   
    public string UserName { get; set; }

    [Required, DataType(DataType.EmailAddress), MaxLength(100), Display(Name = "Email address")]   
    public string Email { get; set; } 
}

View:

<% using (Html.BeginForm()) { %>
    <%: Html.ValidationSummary(true) %>
    <legend>MyAccount</legend>

        <div class="editor-label">
            <%: Html.LabelFor(model => model.UserName) %>
        </div>
        <div class="editor-field">
            <%: Html.EditorFor(model => model.UserName) %>
            <%: Html.ValidationMessageFor(model => model.UserName)%>
        </div>
        <%: Html.Partial("CreateOrEdit", Model) %>
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
<% } %>

Controller:

    //
    // GET: /MyAccount/Create

    public ActionResult Create()
    {
        return View();
    } 

    //
    // POST: /MyAccount/Create

    [HttpPost]
    public ActionResult Create(MyAccount myaccount)
    {
        if (ModelState.IsValid) {
            myaccountRepository.InsertOrUpdate(myaccount);
            myaccountRepository.Save();
            return RedirectToAction("Index");
        } else {
            return View();
        }
    }

Repository:

public class MyAccountRepository : IMyAccountRepository
{
    Par4ScoreContext context = new Par4ScoreContext();

    public IQueryable<MyAccount> All
    {
        get { return context.MyAccounts; }
    }

    public IQueryable<MyAccount> AllIncluding(params Expression<Func<MyAccount, object>>[] includeProperties)
    {
        IQueryable<MyAccount> query = context.MyAccounts;
        foreach (var includeProperty in includeProperties) {
            query = query.Include(includeProperty);
        }
        return query;
    }

    public MyAccount Find(string id)
    {
        return context.MyAccounts.Find(id);
    }

    public void InsertOrUpdate(MyAccount myaccount)
    {
        if (myaccount.UserName == default(string)) {
            // New entity
            context.MyAccounts.Add(myaccount);
        } else {
            // Existing entity
            context.Entry(myaccount).State = EntityState.Modified;
        }
    }

    public void Delete(string id)
    {
        var myaccount = context.MyAccounts.Find(id);
        context.MyAccounts.Remove(myaccount);
    }

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

public interface IMyAccountRepository
{
    IQueryable<PlayerAccount> All { get; }
    IQueryable<PlayerAccount> AllIncluding(params Expression<Func<MyAccount, object>>[] includeProperties);
    MyAccount Find(string id);
    void InsertOrUpdate(MyAccount playeraccount);
    void Delete(string id);
    void Save();
}

Error in MyAccountRepository.Save():

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException was unhandled by user code:  
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at MyProject.Models.MyAccountRepository.Save() 

….

InnerException: System.Data.OptimisticConcurrencyException
Message=Store update, insert, or delete statement affected an unexpected number of rows (0).    
Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Source=System.Data.Entity
StackTrace:
    at System.Data.Mapping.Update.Internal.UpdateTranslator.ValidateRowsAffected(Int64 rowsAffected, UpdateCommand source)
    at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
    at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
    at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
    at System.Data.Entity.Internal.InternalContext.SaveChanges()
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T04:04:42+00:00Added an answer on May 24, 2026 at 4:04 am

    Since MVC model binder will assign an empty string to UserName you can check whether its new or not by using string.IsNulOrEmpty(playeraccount.UserName). You can use IsNullOrWhiteSpace if you treat spaces as empty.

    public void InsertOrUpdate(MyAccount myaccount)
    {
        if (string.IsNulOrEmpty(myaccount.UserName)) {
            // New entity
            context.MyAccounts.Add(myaccount);
        } else {
            // Existing entity
            context.Entry(myaccount).State = EntityState.Modified;
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want use html5's new tag to play a wav file (currently only supported
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
We're building an app, our first using Rails 3, and we're having to build
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.