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

  • SEARCH
  • Home
  • 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 5999837
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T00:36:31+00:00 2026-05-23T00:36:31+00:00

I get an error telling me that: The EntityKey property can only be set

  • 0

I get an error telling me that: “The EntityKey property can only be set when the current value of the property is null.” when I try to save an object with related object.
Here’s my code:

public partial class Cat{
    public bool Save()
    {
        try
        {
            using (var context = new PhonebookEntities())
            {
                if (this.ParentCat != null)
                {
                    if (this.ParentCat.CategoryID == 0)
                        context.AddToCats(this.ParentCat);
                }
                context.AddToCats(this);
                context.SaveChanges();
            }
            return true;
        }
        catch (System.Exception)
        {
            return false;
        }
}

And here I create a Cat object and connect it to a relatet parent Cat object and then call the save method:

        var cat = new Cat()
        {
            CatName = "Test",
            ParentCat = Cat.GetById(1)
        };
        cat.Save();
  • 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-23T00:36:31+00:00Added an answer on May 23, 2026 at 12:36 am

    Let me guess – the Cat.GetById(1) looks like:

    public static Cat GetById(int id)
    {
         using (var context = new PhonebookEntities())
         {
              return context.Cats.Single(c => c.Id == id);
         }
    }
    

    You are using two different contexts – that is the source of the issue. The first context loads the Cat and fills it EntityKey but the second context doesn’t know this instance so once you call AddToCats it will add both new Cat and ParentCat as well but it fails because new entity cannot have filled EntityKey (I know that it is not a new entity but for the new instance of the context it is!).

    Add based operations always add all unknown entities in the object graph. The entity is known by the context only if the same context loaded the entity or if you called .Attach for that entity.

    Because of that, this is also incorrect:

    if (this.ParentCat != null)
    {
         if (this.ParentCat.CategoryID == 0)
             context.AddToCats(this.ParentCat);
    }
    

    Unknown ParentCat will be added automatically together with the current Cat. If you call this it will also add the current Cat but the next call will try to add it again => you will probably get an exception.

    This whole can be solved by two ways:

    • Load the ParentCat on the same context instance as you save Cat
    • Don’t load the ParentCat and either use dummy class or try to set EntityKey

    Dummy class approach:

    var parentCat = new Cat() { Id = 1 };
    context.Cats.Attach(parentCat); // Use correct entity set name
    var cat = new Cat()
    {
        CatName = "Test",
        ParentCat = parentCat
    };
    cat.Save();
    

    EntityKey aproach (this is more like a guess):

    var cat = new Cat()
    {
        CatName = "Test",
        // I hope ParentCatReference will be initialized
        ParentCatReference.EntityKey = new EntityKey("Cats", "Id", 1) // Use correct entity set name
    };
    cat.Save();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When I'm creating temp tables I get an error message telling me that the
When we try to create a view within a funcion we get ERROR: there
If I set pre-compile script into binary code to true I get error saying
How do I unit test my code that has LTS Datacontext. I get error
I get this error: Can't locate Foo.pm in @INC Is there an easier way
How can I make the following code work? During compilation I get an error
I have this query and I get error Operand should contain 1 column(s), whats
What is the best way to get error messages from a WF4 workflow back
In our application we've run into an error numerous times where we get error
I use the following jquery statements but i get error in this function onGetDataSuccess(result)

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.