简体   繁体   中英

C# MVC 4 - Dynamically calling models from a single controller action

I have an Admin controller that needs to delete UIDs from about multiple different models. Can I select the model by passing a string? Here is an example controller action of what I would like to do (of course this doesn't work):

private ModelEntities db = new ModelEntities();

public ActionResult ConfirmDelete(String ModelNameString, Int32 id)
{
    ModelNameString data = db.ModelNameString.Find(id);
    return View(data);
}

Are there any other ways to combine standard tasks for all models into a single controller action? Thank you.

As discussed, implement an interface (eg IDynamicTable) and perform your data operations (eg Delete) with a mapping file?

Example: When you call YourObject.Delete(), you can check the Type of your YourObject . You can do something like this in your Action :

public ActionResult ConfirmDelete(IDynamicTable obj)
{
   // ...
   if (obj is Company)
   {
      // Delete in company table
      return View("Company");
   }
   if (obj is User)
   {
      // Delete in user table
      return View("User");
   }
   // ... 
}

Do not forget that ASP.Net MVC is not PHP+Zend.

If you're concerned about leaving other entities behind after deleting the main reference, you should consider doing a cascading delete. This means that when you delete the main object with the primary key, it will delete all other objects that reference this primary key.

If you have a one to many required relationship, you could do this to have your objects perform a cascading delete. You could either add a [Required] attribute on your required relationships in your models so that the Entity Framework will know the relationship is required or use the Fluent API.

public class Product
{
    public Guid ProductId { get; set; }
    [Required]
    public Category Category { get; set; }
}

Fluent API

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().HasRequired(p => p.Category).WithMany();
}

If your relationship is optional but you want cascading delete, you could do this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>().HasOptional(p => p.Category).WithMany().WillCascadeOnDelete(true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM