Click here to Skip to main content
14,032,300 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hi, I have 2 tables

public class User 
{

        
        public int Id { get; set; }

        public string Name { get; set; }
        public string Password { get; set; }
         
        public virtual Organization Organization { get; set; }
}


 public class Organization
    { 
        public int Id { get; set; }

        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public string Password { get; set; } 

        public override bool Equals(object obj)
        {
            Organization that = obj as Organization;

            if (that != null)
            {
                return (this.Id == that.Id);
            }

            return base.Equals(obj);
        }
    }


While trying to insert row into User I get following error.

Cannot insert explicit value for identity column in table 'Organizations' when IDENTITY_INSERT is set to OFF.



Code is as following


[HttpPost]
       public async Task<IActionResult> Post([FromBody]User p_User)
       {
           try
           {
               using (var dataContext = new AspCoreContext(AspCoreContext.BuildOptions()))
               {
                   dataContext.Users.Add(p_User);


                   await dataContext.SaveChangesAsync();
                   return Ok(p_User);
               }
           }
           catch (Exception ex)
           {
               const string msg = "Unable to insert user";
               Globals.ErrorLogger(ex, msg);
               return StatusCode((int)HttpStatusCode.InternalServerError, msg);
           }
       }


While request body is

{ 
        "name": "Qadeer",
        "password": "123456",
        "token": null,
        "organization": {"Id": "1"}
}


What I have tried:

tried settings relational notations
Posted
Updated 22-Feb-19 4:20am

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

It says you're trying to insert a new value into an IDENTITY column (which generates it own values).

If you put a [Key] attribute on the "Id" (i.e. the "key" field that matches the IDENTITY column) property it will probably fix your problem.
   
Comments
Qadeer Ahmed Khan 22-Feb-19 10:28am
   
Didn't work. I added [Key] to both classes and yet still same. If I send Organization as null in json it works fine. Not sure why it is trying to insert data in Organizations table while it should just insert relation key into it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.190419.4 | Last Updated 22 Feb 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100