c# - EF Code First The INSERT statement conflicted with the FOREIGN KEY constraint -


When I try to insert a record in the database, I get this error message:

< Blockquote>

The foreign key barrier in INSERT statement is contradictory with "FK_dbo.Order_dbo.AspNetUsers_UserId". The conflict occurred in the database "Test", the table "dbo.AspNetUsers", column 'id' has been terminated. Disclaimer: I know that this question has been asked before (and more), but no answer helped me fix this error.

; Set; } [Required] Public string UserId {get; Set; } Public Virtual List & lt; OrderDetails & gt; Order-details {get; Set; } [Foreign key ("userid")] public virtual application user user {receives; Set; }} [TABLE ("order-description")] Public category order descriptions {{Database-generated attribute (database generated identity), key] Public IIT (Receive); Set; } [Required] Public IR order command {get; Set; } [Foreign order ("order ed")] public virtual order order {get; Set; }} Public class ApplicationUser: IdentityUser {[MaxLength (15)] Public String FirstName {get; Set; } [Maxlenda (15)] Public String LastName {get; Set; } [MaxLenth (50)] Public String Email Address {Received; Set; } Public Virtual List & lt; Order & gt; Order Received; Set; }}

code which includes the new order :

  giving public order (dynamic addOrderDetails, string user id) { If (AddOrderDetails.OrderId == faucet) {var order = new order () {UserId = userId, CreateDate = DateTime.Now, status = OStatus.In progress, confirmation = (datetime?), Tap}}; Var newOrder = _dbContext.Orders.Add (order); _dbContext.Entry (command) .set = EntityState.Added; _dbContext.SaveChanges (); // This is where the error message is being thrown. Var orderDetails = New OrderDetails () {OrderId = newOrder.Id, ServiceId = addOrderDetails.ServiceId, EventStart = start, EventEnd = end}; Var newOrderDetails = _dbContext.OrderDetails.Add (orderDetails); _dbContext.Entry (orderDetails) .set = EntityState.Added; _dbContext.SaveChanges (); } Return tap; }  

Error thrown on this line: _dbContext.SaveChanges (); // This is where the error message is being inserted.

While debugging, I can see that the value of UserId = userId, is.

So why am I getting this error message?

aspNetUsers should have a record in database in the UserId The value you set in the column is in the new order from userId . See not only required Order.UserId , but a foreign key for the aspNetUsers table ( [ForeignKey ("UserId")] in the attribute Order ). Therefore, it is not enough that User ID is a value (! = Null), it should contain a value that is aspNetUsers table.

Exception means that such a record is not present in the aspNetUsers table.


Comments