C# DbContext.addchanges一个实体';s属性值
调用方法C# DbContext.addchanges一个实体';s属性值,c#,entity-framework-core,C#,Entity Framework Core,调用方法DbContext.Add时,实体的属性值正在更改,我不知道原因: 我有以下代码(context是一个注入的字段,从类DbContext派生): 这是城市类: public class City { [Required] [Key] public int Id { get; set; } [Required] public string Text { get; set; } [Required] public int State
DbContext.Add
时,实体的属性值正在更改,我不知道原因:
我有以下代码(context
是一个注入的字段,从类DbContext
派生):
这是城市
类:
public class City {
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
[Required]
public int StateId { get; set; }
public virtual State State { get; set; }
}
public class State {
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
}
这是状态
类:
public class City {
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
[Required]
public int StateId { get; set; }
public virtual State State { get; set; }
}
public class State {
[Required]
[Key]
public int Id { get; set; }
[Required]
public string Text { get; set; }
}
在运行
context.Add(item)
之前,实体项的值是Text=“New York”
和StateId=1
。但是当我单步执行它时,StateId
被分配给0
。我不知道为什么会这样。你能帮帮我吗?城市的关键是什么?听起来像是地图问题。映射是什么,您是否为State
属性设置了任何内容?我忘了添加City
的键,刚刚更新了我的问题,并且我还将State
类放入。映射是builder.Entity().HasIndex(x=>new{x.Text,x.StateId}).IsUnique()
和builder.Entity().HasIndex(x=>x.Text).IsUnique()代码>将实体添加到上下文时,城市
的状态
属性是否包含任何值?是的,它包含状态
的初始化实例,Id=0
和文本=null
(默认值)。