【问题标题】:entity framework change reference of a nested object嵌套对象的实体框架更改引用
【发布时间】: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


【解决方案1】:

人应该是这样的

public class Person{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int Id{get;set;}
    public string Name {get;set;}
    [ForeignKey("Cartype ")]
    public int CarTypeID{get;set;}
    public CarType Cartype {get;set;}
 }

之后,您可以使用以下方法更改 Person 对象中的 CarType 下面的代码

person.CarTypeID= carType.Id;
dbContext.SaveChanges();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2011-10-28
    • 2012-11-02
    相关资源
    最近更新 更多