How to use referenced assembly for controller scaffolding

asp.net-mvc asp.net-mvc-scaffolding c# entity-framework-6

Question

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

1
4
5/2/2017 9:58:12 AM

Accepted Answer

Scaffolding with referenced assemblies compiled as dll-file simply doesn't work. It was necessary to add reference to the project which contains the model classes. Then it worked as expected. Is this a bug or a feature?

0
5/2/2017 9:58:58 AM

Popular Answer

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; }
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow