First of all I am using ASP.NET MVC 4 and Entity Framework 5. And this is my first project in MVC.
I am trying to insert a row to my WorkLogs Table. I have created my database with code first approach.
This is my WorkLogs Model (Since I created database, I didn't make any change to my model):
public class WorkLogs
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int WorkLogId { get; set; }
[Required]
public int Time { get; set; }
[Required]
public DateTime Date { get; set; }
[Required]
public DateTime CreatedDate { get; set; }
[Required]
public bool IsSent { get; set; }
public virtual Users User { get; set; }
public virtual Works Work { get; set; }
}
This model has created this table in database:
And these are relationships (It seems correct to me):
I am trying to add a new row with this code in my controller:
WorkLogs log = new WorkLogs()
{
Time = iTime,
Date = beginWeek.AddDays(i),
CreatedDate = DateTime.Now,
User = userObj,
Work = workObj,
IsSent = true
};
_db.WorkLogs.Add(log);
_db.SaveChanges();
When I run this, it throws an exception in _db.SaveChanges(); line.
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.
I understand there is a problem with relationships when I see this exception. And I also understand I am trying to insert an object to a column which wants an integer. But I don't understand that it created the User_UserId and Work_WorkId columns and gave them int data type. But in controller, it wants a user object.
My model, controller might be all wrong. But as I said I'm new in EF and MVC.
What changes I should do to insert a WorkLog to my database?
I hope I made myself clear.
Any help would be appreciated.