Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have 2 tables

C#
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

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.
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900