invernomuto
invernomuto

Reputation: 10211

Fluent configuration of relationship

In my model I have some entities which refer to an instance of 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 to do is implement delete cascade of Images by delete of NewsArticles and other entities

[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 override of OnModelCreating what is the right option of declaring the relationship of every entity which refer 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);
    }

Upvotes: 3

Views: 76

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

I think want you need is replacing WithOptionalPrincipal() with WithMany() as long as Image entity doesn't have collection of NewsArticles.

Config

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 Image has NewsArticles and Staffs collection property, the 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 NewsArticle table in database will have generated Image_ID column in the database since you are using independent association (there is no ImageID property on NewsArticle).

The Image table in the database will not have any additional column.

Deleting an Image will also delete any NewsArticle or Staff that refers to current deleted image.

Upvotes: 2

Related Questions