How can I update the Code First app to make changes to the manual schema?

I have an application that was created using EF. The problem is that I noticed some extraneous foreign key columns created in one of the tables. Deleting these columns raises an error [SqlException (0x80131904): Invalid column name "Material_Id".

Here is a simplified version of the class structure ...

public class Hazard { public int Id { get; set; } public string Name { get; set; } } public abstract class HazardAnalysis { public int Id { get; set; } public int HazardId { get; set; } public virtual Hazard Hazard { get; set; } } public class ProductHazard : HazardAnalysis { public int ProductId { get; set; } public virtual Product Product { get; set; } } 

The created table looked like this:

 dbo.Hazards Id int Name string Product_Id int 

Since the relationship between product hazards and hazards is 1: many, the Product_Id field should not be there. Deleting this column generates an invalid column name "Product_Id".

I looked at the model for several hours and cannot find a valid reason for the existence of this column.

Is there a way to update the model after manually deleting the column? I obviously do not want to drop and recreate the database.

I also noticed that the productId of the current product is inserted into the dbo.Hazards table Product_Id whenever a new ProductHazard is created. Because there is a one-to-one relationship between dangerous products and hazards when a new ProductHazard is created, the ProductIId field is updated by the ProductId of the new ProductHazard, which seems strange.

Any advice is appreciated.

Here is the DbSet code:

 public DbSet<Hazard> Hazards { get; set; } public DbSet<HazardAnalysis> HazardAnalyses { get; set; } 

and...

 modelBuilder.Entity<HazardAnalysis>() .HasRequired(e => e.Hazard) .WithMany() .HasForeignKey(e => e.HazardId) .WillCascadeOnDelete(false); 
+4
source share
1 answer

You need to define many parts of a relationship. In this case, you need to add the collection property to your Hazard object, as shown below:

 public class Hazard { public int Id { get; set; } public string Name { get; set; } public virtual ICollection<HazardAnalysis> HazardAnalyses { get; set; } } 
0
source

Source: https://habr.com/ru/post/1447878/


All Articles