我定义了以下 C# Entity Framework 代码第一个实体:
class Program
{
static void Main(string[] args)
{
var context = new MyContext();
var person = new Person
{
FirstName = "Nadege",
LastName = "Deroussen",
BirthDate = DateTime.Now,
AccessCode = new AccessCode { Code = "ABC" }
};
context.Persons.Add(person);
var accessCode = new AccessCode { Code = "MGH" };
context.AccessCodes.Add(accessCode);
context.SaveChanges();
var person = context.Persons.Where(e => e.Id == 1).Single();
person.AccessCodeId = 2;
context.SaveChanges();
Console.Write("Person saved !");
Console.ReadLine();
}
}
public class Person
{
public int Id { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime BirthDate { get; set; }
public int AccessCodeId { get; set; }
[ForeignKey("AccessCodeId")]
public virtual AccessCode AccessCode { get; set; }
}
public class AccessCode
{
public int Id { get; set; }
public string Code { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Person> Persons { get; set; }
public DbSet<AccessCode> AccessCodes { get; set; }
}
在Main
方法中,分配后AccessCodeId = 2
,如果我检查AccessCode
人员中的引用,它仍然指向AccessCode
with Id == 1
。我怎样才能得到这个自动更新?
我正在学习EF,所以如果这没有意义,请原谅。