简体   繁体   中英

EF Code First ForeignKey not Updated

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 ?

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; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM