Reputation: 165
Im trying to Update a record in the database. The data for this Record comes from an MVC Api call
In the object which came from the Api Call the reference to a Customer has been changed.
The Class:
public class Visit
{
public int Id { get; set; }
public DateTime Start { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
public int Id { get; set; }
}
The API Change excerpt:
db.Entry(visit).State = EntityState.Modified;
if (visit.Customer.Id == 0) db.Entry(visit.Customer).State = EntityState.Added;
try
{
db.SaveChanges();
}
When i check the visit object, i see that the Customer Property of the visit is different from the original, but tracing the db.SaveChanges(); Shows no changes to the [Customer_Id] of the table....
exec sp_executesql N'update [dbo].[Visits]
set [StartVisit] = @0, [EndVisit] = null, [Activities] = @1, [Paid] = @2
where ([Id] = @3)
',N'@0 datetime2(7),@1 nvarchar(max) ,@2 bit,@3 int',@0='2014-08-31 14:21:26.7800000',@1=N'text ',@2=0,@3=33
Why does the EF not see this Change ? Or, what do i have to do so the EF sees the Change, and updates the Customer_Id record ?
Upvotes: 1
Views: 70
Reputation: 359
Do not just use Id. Instead use VisitId and CustomerId. When you add a foreign key you must add the FK and an instance of that class so that the column exists in the db.
public class Visit
{
public int VisitId { get; set; }
public DateTime Start { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
public int CustomerId{ get; set; }
}
Upvotes: 2