为了账号安全,请及时绑定邮箱和手机立即绑定

C# 无法从 DbContext 中删除对象

C# 无法从 DbContext 中删除对象

C#
心有法竹 2022-01-15 15:41:28
大家好,我正在尝试更新我的本地 sqldb,但没有成功。我创建了一个 DbContext:    public class DbContextWeather1 : DbContext    {        public DbSet<WeatherRoot> Weathers { get; set; }}WeatherRoot 在哪里:public class Coord{    [JsonProperty("lon")]    public double Longitude { get; set; }     [JsonProperty("lat")]    public double Latitude { get; set; } }public class Sys{    [JsonProperty("country")]    public string Country { get; set; } }public class Weather{    [JsonProperty("id")]    public int Id { get; set; }    [JsonProperty("main")]    public string Main { get; set; }    [JsonProperty("description")]    public string Description { get; set; }     [JsonProperty("icon")]    public string Icon { get; set; }}public class Main{    [JsonProperty("temp")]    public double Temperature { get; set; }     [JsonProperty("pressure")]    public double Pressure { get; set; }     [JsonProperty("humidity")]    public double Humidity { get; set; }     [JsonProperty("temp_min")]    public double MinTemperature { get; set; }     [JsonProperty("temp_max")]    public double MaxTemperature { get; set; } }public class Wind{    [JsonProperty("speed")]    public double Speed { get; set; }     [JsonProperty("deg")]    public double WindDirectionDegrees { get; set; } }public class Clouds{    [JsonProperty("all")]    public int CloudinessPercent { get; set; } }我收到此错误:The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Weathers_dbo.WeatherRoots_WeatherRoot_Name". The conflict occurred in database "WeatherApp.DataProtocol.DbContextWeather1", table "dbo.Weathers", column 'WeatherRoot_Name'.The statement has been terminated.我试图谷歌它,但只找到相关的密钥,这不是我的情况。有没有人能帮帮我,我有点无奈。谢谢。
查看完整描述

2 回答

?
大话西游666

TA贡献1817条经验 获得超14个赞

这是由于外键约束而发生的。在删除父记录之前,您必须删除所有引用的子记录。

根据您的业务逻辑修改后尝试应用以下代码并让EF处理它。

                 modelBuilder.Entity<Parent>()
                .HasMany<Child>(c => c.Children)
                .WithOptional(x => x.Parent)
                .WillCascadeOnDelete(true);

如果您不确定关系是如何建立的,请使用 SQL Server 观察表并检查键和约束,如下所示

//img1.sycdn.imooc.com//61e27aeb00015e4a04700290.jpg

查看完整回答
反对 回复 2022-01-15
?
长风秋雁

TA贡献1757条经验 获得超7个赞

从 DbSet.Remove 上的 MSDN 页面:“将给定实体标记为已删除,以便在调用 SaveChanges 时将其从数据库中删除。请注意,在调用此方法之前,该实体必须以其他状态存在于上下文中。”

https://msdn.microsoft.com/en-us/library/system.data.entity.dbset.remove(v=vs.113).aspx

您可以尝试添加:

db.SaveChanges();

在您的召唤下:

db.Weathers.Remove(bye);


查看完整回答
反对 回复 2022-01-15
  • 2 回答
  • 0 关注
  • 338 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号