C#无法从DbContext中删除对象

问题描述 投票:1回答:2

大家好我正在尝试更新我的本地sql db但没有成功。 我创建了一个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; } 
}

public class WeatherRoot
{
    [JsonProperty("coord")]
    public Coord Coordinates { get; set; }

    [JsonProperty("sys")]
    public Sys System { get; set; } 

    [JsonProperty("weather")]
    public List<Weather> Weather { get; set; } 

    [JsonProperty("main")]
    public Main MainWeather { get; set; } 

    [JsonProperty("wind")]
    public Wind Wind { get; set; } 

    [JsonProperty("clouds")]
    public Clouds Clouds { get; set; } 

    [JsonProperty("id")]
    public int CityId { get; set; } 

    [JsonProperty("name")]
    [Key]
    public string Name { get; set; } 

    [JsonProperty("dt_txt")]
    public string Date { get; set; } 

    [JsonIgnore]
    public string DisplayDate => DateTime.Parse(Date).Hour.ToString();
    [JsonIgnore]

    public string DisplayTemp => $"{MainWeather?.Temperature ?? 0}° 
    {Weather?[0]?.Main ?? string.Empty}";

    [JsonIgnore]
    public string DisplayIcon => $"http://openweathermap.org/img/w/{Weather? 
    [0]?.Icon}.png";
    [JsonIgnore]
    public string Icon => Weather?[0]?.Icon;
    //[JsonIgnore]
    //public string DisplayDescription => $"{Weather?[0]?.Description}";
}

但是当我试图删除一个特定的对象时:

  public void SaveWeather(WeatherRoot weather)
        {

        using (var db = new DbContextWeather1())
        {
            db.Database.CreateIfNotExists();
            //var tmp = db.Weathers;
            if (db.Weathers.Any(W => W.Name.Equals(weather.Name)))
            {
                var bye = (from x in db.Weathers
                           where x.Name.Equals(weather.Name)
                           select x).FirstOrDefault();

                db.Weathers.Remove(bye);

                db.Entry(bye).State = System.Data.Entity.EntityState.Deleted;

            }
            var w = new WeatherRoot()
            {
                CityId = weather.CityId,
                Clouds = weather.Clouds,
                Coordinates = weather.Coordinates,
                Date = weather.Date,
                MainWeather = weather.MainWeather,
                Name = weather.Name,
                System = weather.System,
                Weather = weather.Weather,
                Wind = weather.Wind
            };
            if (w.Date == null)
            {
                w.Date = DateTime.Now.ToString();
            }
            db.Weathers.Add(w);
            db.SaveChanges();


        }
    }

我收到此错误:

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.

我试图谷歌它,但只找到相关的密钥,这不是我的情况。 有没有人可以帮我这个,我有点无奈。 谢谢。

c# entity-framework foreign-keys dbcontext sqldb
2个回答
1
投票

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

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

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

如果您不确定如何建立关系,请使用SQL Server观察表并按如下方式检查Keys和Constraints

enter image description here


0
投票

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

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

您可以尝试添加:

db.SaveChanges();

在你的电话下:

db.Weathers.Remove(bye);
© www.soinside.com 2019 - 2024. All rights reserved.