Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use referenced assembly for controller scaffolding

I have a class library with some model classes and a DbContext class (all those classes are public). This class library is referenced by an MVC-5 application.

Is it possible to use the model classes from that referenced class library for scaffolding of a controller in that MVC-5 application?

When I use Controllers - Add - Controller - MVC Controllers with views, using Entity Framework then in the dialog both comboboxes for Model class and for Data context class do not contain any items. When I fill in the fully qualified name of the class from referenced class library, then the Add button is still disabled. What am I doing wrong?

enter image description here

like image 599
Daniel Dušek Avatar asked Nov 10 '22 05:11

Daniel Dušek


1 Answers

With a bit of tweaks you can reference an external dll (ex. Entity Framework project) using scaffolding.

To do so, you need to create a class that inherits your EF table class. In order to work you need to use the [Table] attribute on top of your class with the right schema and table name or else scaffolding will create a new table.

Also make sure you use the "new" keyword and overload the id. You will need to use the [Key] attribute (if has not already been defined in your EF table in the original dll).

Finally create a new dbcontext and make sure you use the connection string id in your web.config.

This should allow you to reference the table and the context in your web project.

Here is my code (very simple) and hope this helps.

namespace ConsoleAdmin.Models
{
    [Table("ntf.tblNotification_ntf")]
    public class Notification : tblNotification_ntf
    {
        [Key]
        public new int notificationId { get; set; }
    }

    public class NotificationDbContext : DbContext
    {
        public NotificationDbContext(): base("name=bd_Soquij_logEntities") { }

        public DbSet<Notification> Notifications { get; set; }
    }
}
like image 58
Jean-Sebastien Avatar answered Nov 14 '22 21:11

Jean-Sebastien