【发布时间】:2020-10-07 08:05:32
【问题描述】:
这是一个简单的问题,但我似乎找不到解决方案。 我有两个类如下:
public class Person{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id{get;set;}
public string Name {get;set;}
public CarType Cartype {get;set;}
}
public class CarType{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int Id{get;set;}
public string Type {get;set;}
public string CompanyLocation {get;set;}
}
假设我有两个 CarType 如下:
1 Mercedes Berlin
2 Chevrolet Detroit
我有一个人如下:
1 Mike 2 (2 is the foreign key to `CarType`)
问题是,如何将 Mike 的 CarType 更改为 1(即更改对表 CarType 中另一行的引用)?
这是我的代码:
Person person = dbContext.Persons.Single(c => c.Id == 1);
CarType carType= dbContext.CarTypes.Single(c => c.Id == 1);
person.CarType= carType;
我尝试了找到here的答案
但我在执行dbContext.SaveChanges() 时仍然遇到同样的错误:
属性“Id”是对象的关键信息的一部分,不能 修改
问题是我不想更新它的引用 CarType,我想将引用更改为另一行
【问题讨论】:
-
进行更新的代码在哪里?听起来好像是错的。
-
您可以将您的尝试添加到问题中吗?
-
@Neil 我将其添加到问题中
-
@JohnathanBarclay 我编辑了问题并添加了我的尝试
-
您的关系是如何配置的?
CarType.Id是否用作Person的外键?
标签: c# entity-framework dbcontext