Free configuration of relations

In my model, I have several objects that reference an instance of the Image class

    public class Image
  {
    public int ID { get; set; }

    public string URL { get; set; }

  }

public abstract class TeamBase
  {

    public Image Image { get; set; }

  }

public class NewsArticle
{      
  public Image Image { get; set; }

}

      

enter image description here

What I would like to do is implement removing the cascade of images by removing from NewsArticles and other objects

[Authorize]
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
  NewsArticle newsArticle = _repository.Get((int)id);
  _repository.Delete(newsArticle);
  _repository.Save();      
  return RedirectToAction("Index");
}

      

So, in the OnModelCreating override, what is the correct option to declare a relationship for every entity that references an Image instance? Is the following approach the right choice?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
      base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<NewsArticle>()
                    .HasOptional(n => n.Image)
                    .WithOptionalPrincipal()
                    .WillCascadeOnDelete(true);

        modelBuilder.Entity<Staff>()
                    .HasOptional(n => n.Image)
                    .WithOptionalPrincipal()
                    .WillCascadeOnDelete(true);
    }

      

+3


source to share


1 answer


It seems to me you need to replace WithOptionalPrincipal()

with WithMany()

while the object Image

has no collection NewsArticles

.

Configuration

modelBuilder.Entity<NewsArticle>()
            .HasOptional(n => n.Image)
            .WithMany()  // no collection property on Image
            .WillCascadeOnDelete(true);

modelBuilder.Entity<Staff>()
            .HasOptional(n => n.Image)
            .WithMany() // no collection property on Image
            .WillCascadeOnDelete(true);

      

If it Image

has a collection property NewsArticles

and Staffs

, WithMany()

should mention it, WithMany(x => x.NewsArticles)

and WithMany(x => x.Staffs)

.



public class Image
{
    public ICollection<NewsArticle> NewsArticles { get; set; }
    public ICollection<Staff> Staffs { get; set; }
}

      

The table NewsArticle

in the database will create a column Image_ID

in the database since you are using an independent association (there is no property in NewsArticle ImageID

).

There Image

will be no extra column in the table in the database.

Deletion Image

will also delete any NewsArticle

or Staff

that pertain to the currently deleted image.

+2


source







All Articles