Ali
Ali

Reputation: 99

1 controller to deal with 2 models, ASP.NET ,MVC5

I'm working on a bilingual website, i.e. Persian (=Farsi) and English. I've created two sets of models, one for each object, and they inherit from one master object. For example, the Book class:

public class Book
{
    public int id { get; set; }
    public string title { get; set; }
    ...
}

public class Book_fa : Book {
    public PersianMonth? month { get; set; }
    ...
}

public class Book_en : Book { 
    public EnglishMonth? month { get; set; }
    ...
}

(both PersianMonth and EnglishMonth are enum)

And these objects are stored in two tables:

public class myDbContext : DbContext
{
    public myDbContext()
        : base("name=myDbName")
    {
    }

    public DbSet<Book_fa> Books_fa { get; set; }
    public DbSet<Book_en> Books_en { get; set; }
}

I can create a separate controller and views for each object. For example, the Delete action in Book_faController:

private myDbContext db = new myDbContext();

public ActionResult Delete(int id)
{
    Book_fa book_fa = db.Books_fa.Find(id);
    db.Books_fa.Remove(book_fa);
    db.SaveChanges();
    return RedirectToAction("Index");
}

But the Delete action in Book_enController is the same! Except the db.Books_fa term which must changed to db.Books_en. This is true for any other action (create, edit, listing, ....).

So i decided to use just one controller to deal with these bilingual books! I've tried this:

public ActionResult Anything(string lang, ...)
{
    var table = getTable(lang);
    ...
}

private DbSet getTable(lang)
{
    return (lang == "fa") ? db.Books_fa : db.Books_en;
}

But this is not working :(

Can anyone help me solve this?

Upvotes: 1

Views: 64

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could return an IDbSet<Book> from your GetTable method:

private IDbSet<Book> GetTable(string lang)
{
    return lang == "fa" ? (IDbSet<Book>)db.Books_fa : (IDbSet<Book>)db.Books_en;
}

Now you will have all the OrderBy, ToList, ... method at your disposal on the result of this method so that you can continue filtering the results without eagerly executing the SQL query yet, just building the expression tree.

Upvotes: 2

Related Questions