1

Hi everyone I am trying to update my local sqldb without success.
I created a DbContext:

    public class DbContextWeather1 : DbContext
    {
        public DbSet<WeatherRoot> Weathers { get; set; }
}

Where WeatherRoot is:

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}";
}

But when I am trying to delete a specific object:

  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();


        }
    }

I get this error:

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.

I tried to google it, but only found related keys, which is not my case.
Does anyone can help me with this, I kind of helpless.
Thanks.

Kushan Randima
  • 2,174
  • 5
  • 31
  • 58
Elizabeth
  • 282
  • 1
  • 6
  • 16
  • The error message *IS* related to (foreign) keys. Please edit your question to include the `CREATE TABLE` statements of your tables, including the foreign key references. – Progman Sep 12 '18 at 22:21
  • But I didn't create any table, besides the above code. – Elizabeth Sep 12 '18 at 22:24
  • You have to load and delete the referenced objects linked to your `WeatherRoot` object as well (`Weathers`, `MainWeather`, `Wind`, `Clouds`, `Coordinates`). – Progman Sep 12 '18 at 22:31
  • And how can I locate them? – Elizabeth Sep 12 '18 at 22:43
  • They are properties of your `WeatherRoot` object. You need to load them with an `Include()` statement (not sure if that is possible in a LINQ query) or use `db.Entry().Reference().Load()` and `db.Entry().Collection().Load()`. As you don't have any other `DbSet<>` properties in your context you have to remove them with a `db.Entry().State=...` call. – Progman Sep 12 '18 at 23:00

2 Answers2

1

This happens due to a foreign-key constraint. You have to remove all the referenced child records before deleting the parent record.

Try to apply the following code after modifying it according to your business logic and let EF deal with it.

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

If you are not sure about how the relationships are made, please observe the tables using SQL Server and examine Keys and Constraints as follows

enter image description here

Kushan Randima
  • 2,174
  • 5
  • 31
  • 58
0

From the MSDN page on DbSet.Remove: "Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called. Note that the entity must exist in the context in some other state before this method is called."

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

You could try adding:

db.SaveChanges();

under your call:

db.Weathers.Remove(bye);
Newbie12345
  • 151
  • 7