this may be a simple problem for some of you, but I am have a difficult time trying to resolve it.
I have a Message.cs class:
public class Message : Audit
{
public int MessageId { get; set; }
public string TextBody { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
}
I am using entity framework to have secure log ins and etc. When I post a message, I have set break points to see that the message object that I am sending does contain the UserId, but when db.SaveChanges(); is called, there is an error:
"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_dbo.Messages_dbo.AspNetUsers_ApplicationUser_Id\". The conflict occurred in database \"aspnet-ChatApp-20140708035313\", table \"dbo.AspNetUsers\", column 'Id'.\r\nThe statement has been terminated."
Also, I am using data adapters and interfaces to work with my APIs. my MessageDataAdapter for POST looks like this: (EDITTED LOOK BELOW)
public Models.Message PostMessage(Models.Message newMessage)
{
ApplicationUser user = new ApplicationUser();
Message message = new Message();
newMessage.TextBody = message.TextBody;
newMessage.DateSent = DateTime.Now;
newMessage.Hidden = message.Hidden;
newMessage.UserId = user.Id;
db.Messages.Add(newMessage);
db.SaveChanges();
return newMessage;
}
When I set a breakpoint, newMessage contains the necessary data plus the UserId when I am logged in, for I have it authroized so only "Users" can POST to the DATABASE. However, when it reaches db.SaveChanges that error occurs.
Any ideas on how to resolve this issue?
Thank you!
EDIT
this is what I have(I guess what I really want to be able to do is to be able to POST Message containing the UserId of whoever is logged in):
public Models.Message PostMessage(Models.Message newMessage)
{
ApplicationUser user = new ApplicationUser();
Message message = new Message();
message.TextBody = newMessage.TextBody;
message.DateSent = DateTime.Now;
message.Hidden = newMessage.Hidden;
message.UserId = newMessage.UserId;
db.Messages.Add(message);
db.SaveChanges();
return message;
}
My front end HTML has a input type hidden with the value being "User.Identity.GetUserId()" which I want to be POSTed with the Message.