How do I use asp.net MVC Scaffolder with a context that is two subclasses down from dbcontext - asp.net-mvc-3

I have a standard model set.
I have a base context class that inherits from dbcontext to add some features I needed.
public class MyContext : DbContext
{
public void MyFeature() {
}
}
I then have my actual Data Context:
public class DataContext : MyContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
I want to use the scaffolder built in when you create a controller, but I get an error "Unsupported Context Type"
If I change the datacontext to just inherit from dbcontext directly it works, but at this point I have alot of stuff that uses the added features, so changing the inheritance cant be done without commenting out all that stuff. And I have of course simplified down the features, it is actually quite alot of stuff, so adding it directly into the datacontext would be alot of work, plus the scaffolder should be smart enough to see that the datacontext is a dbcontext.
How can I use the scaffolder with my datacontext?

Why don't you use Composition?
If your feature really is just needed as lets say a few methods needed in those objects I would put those methods in a separate class called ContextDetails - something along those lines and have DataContext contain a ContextDetails like so:
//Changed MyContext to ContextDetails
public class ContextDetails
{
public void MyFeature()
{
//Do something
}
}
public class DataContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public ContextDetails DbDetails { get; set; }
}
And if the ContextDetails object needs information about the DataContext/DbContext it's in pass the DataContext/DbContext into a method or even the constructor.
If you don't like Composition for this problem maybe you want to use an Interface. If that's the case check out http://www.codeproject.com/Tips/309753/Repository-Pattern-with-Entity-Framework-4-1-and-C
The context class must inherit from System.Data.EntityDbContext which provides facilities for querying and working with entity data as objects
The best reason I could find for why the inheritance is not working in your example.
EDIT:
I read my answer and realized DBDetails might not be the best name but you get the idea. Extract the implementation and use it as a separate entity. Good luck!

i think first you should install entity framework 4.0 then i think definitely it's working please try this.

Related

ASP.NET Core MVC - Bind model containing property that uses an interface

I have a model that contains an interface based property, which the concrete implementation being discoverable via another property of the model.
public class SubscriptionViewModel
{
public Guid Id { get; set; }
...
public SubscriptionTypeEnum SubscriptionType { get; set; } // <- Determines the concrete class
public ISubscriptionCriteria SubscriptionCriteria { get; set; } //<- Property based on interface class
...
}
When the interface based property is present the model in the controller comes through as null. If removed, everything binds as expected.
[HttpPost("api/[controller]/[action]")]
public async Task Post([FromBody]SubscriptionViewModel model)
{
...
}
This will be because the controller doesn't know which solid implementation to use for the interface.
Any ideas how I can solve this? It looks like this might be achievable using a custom IModelBinderProvider or BindingBehaviorAttribute?
I guess I could have a SuperSubscriptionCriteria implementation that contains all possible properties used by concrete implementations of ISubscriptionCriteria and then rely on AutoMapper to convert them to the real implementations. But this seems like a hack and would require on-going maintenance as new ISubscriptionCriteria implementations are added.

Giving error while creating partial class

I am developing MVC application in which , I am trying to create the partial class of class generated by MVC application lets say Location class.
Now I want to create the partial class of Location class in new class file.
The below class code is auto genrated by MVC of Location code.
namespace CRM
{
public partial class Location
{
public int Id { get; set; }
public string Name { get; set; }
public string Remark { get; set; }
}
}
I have added new class file which contain the partial class of above file
namespace CRMEntities.Partial_Class
{
public interface ILocation
{
[StringLength(50, ErrorMessage = "Region can accept maximum 50 characters.")]
string Region { get; set; }
[Key]
int Id { get; set; }
[Required]
string Name { get; set; }
string Remark { get; set; }
}
public partial class Location : ILocation
{
}
}
Its giving the below error...
CRMEntities.Partial_Class.Location' does not implement interface member 'CRMEntities.Partial_Class.ILocation.Name
First, you don't need to do this, what I understand is you are trying to do validation right? Think about, the object generated by EF is not ViewModel, they are domain model. Data annotation should be in View Model, not domain model.
Most of cases, often mis-use is to use domain model as view model, but it is not correct much. Because sometime, view models need more than one domain model to provide data for your UI.
So for separation of concerns, you need to define your View Model different with domain model.
Example: you have Location class, you need to add LocationViewModel class and put data annotation in here.
You can map manually or use AutoMapper for mapping bettween View Model and Domain Model.
Another solution is you can use Fluent Validation, with this way, needless to have more partial class just for validation.
You don't show the definition of ILocation in your question, but the error says that the Location.Name property is declared differently than the ILocation.Name member.
Edit: Your two partial classes appear to be in two different namespaces, hence they are actually two entirely different classes, not two parts of the same class. That would explain the compiler error.
Having said that, I do agree with the other answer (+1!) that you should do your UI validation on a view model instead.

What is the best way to create EF DbContext instance for ASP.NET MVC

In order to support lazy loading feature in EF, what is the best way to instantiate DbContext?
I know HttpContext's current item is good place to create DbContext via Application_BeginRequest method and Application_EndRequest method, but in some sample codes of MSDN and official asp.net mvc site, they just create DbContext in Controller's constructor and dispose it in controller's Dispose() method.
I think the both ways are not too different because all of those all implement session per request pattern.
I just want to make sure that my understanding is correct or not.
The Dispose() method in the controller isn't always reliable. By the same token, Session is probably not a good idea either. "Best" is probably subjective, but we've had the best success by using dependency injection (Castle Windsor) and following a Unit of Work Repository pattern.
Setup the unit of work along the following lines:
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork()
{
this.Context = new MyEFEntities();
this.Context.ContextOptions.LazyLoadingEnabled = true;
}
public void Dispose()
{
this.Context.Dispose();
}
public ObjectContext Context { get; internal set; }
}
Setup your repository:
public class Repository<TEntity> : IRepository<TEntity>
where TEntity : class
{
public Repository(IUnitOfWork unitOfWork)
{
Context = unitOfWork.Context;
ObjectSet = Context.CreateObjectSet<TEntity>();
}
public ObjectContext Context { get; set; }
public IObjectSet<TEntity> ObjectSet { get; set; }
}
Register with Castle in Global.asax:
void Application_Start()
{
this.Container.Register(
Component.For<IUnitOfWork>()
.UsingFactoryMethod(() => new UnitOfWork())
.LifeStyle
.Is(LifestyleType.PerWebRequest)
);
ControllerBuilder.Current.SetControllerFactory(
new WindsorControllerFactory(this.Container));
}
And use in your controller (or wherever you're using it, as long as it's injectable):
public class SomeController
{
public SomeController(IRepository<MyEntity> repository)
{
this.Repository = repository;
}
public IRepository<MyEntity> Repository { get; set; }
public ActionResult MyAction()
{
ViewData.Model = this.Repository.ObjectSet.Single(x => x.Condition); //or something...
}
}
Any lazy loading here could potentially be a trap for a future issue. Without DI, without a repository - its hard to see anything working without it being a hack for lazy loading. Also do you you plan on passing your entities to your view. If so this is going to create a bad overlap. The controller should package data for your view, not have things evaluated later in your view.
For MVC best practices, you should flatten out your domain model as much as possible into a viewmodel (if flattening makes sense) and use the view model. Since you would ideally then know what would be lazy loaded, it may make more sense to take the hit up front and use .Include() in your query to eager load, otherwise you can issue many many queries to the database.
I've used a session factory pattern and saved the DBContext in the session object. It will stay open per session. I haven't had problems with it so far.

Serializing EF4.1 Entities using JSON.Net

I am building an application using MVC3, Razor view engine, Repository Pattern with Unit of Work and using EF4.1 Code First to define my data model.
Here is a bit of background (gloss over it if you want).
The application itself is just an Intranet 'Menu'.
The 2 main entities are MenuItem and Department of which:
MenuItem can have many Departments
Departments can have many MenuItems
MenuItem may have a MenuItem as a parent
This is how I have defined my Entities
public class MenuItem
{
public int MenuItemId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public virtual ICollection<Department> Departments { get; set; }
public int? ParentId { get; set; }
public virtual MenuItem ParentMenuItem { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
I am using the FluentAPI to define the Self Reference Many-to-Many for the MenuItem.
The issue I am having is passing a MenuItem to the view via JSON.
The central issues are that I have a circular reference between my entities that the built in JSON parser can't deal with and I have lazy loading and proxy generation still enabled.
I am using JSON.net library from Nuget as my JSON Serializer as this seems to be a nice way round the circular reference issue. I now am unsure how to 'fix' the proxy generation issue. Currently the serializer throws The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.
Can anyone help me with this? If I turn off proxy generation, I am going to have a hell of a time loading all of the MenuItem children so I am keen leave this on. I have read a fair amount and there seems to be a variety of different answers including projecting the entities into another object and serialize that, etc, etc. Ideally there would be some way of configuring JSON.net to ignore the RelationshipManager object?
Update
Here is what I have used as a Custom ContractResolver for JSON.Net serializer. This seems to have sorted out my issue.
public class ContractResolver : DefaultContractResolver
{
private static readonly IEnumerable<Type> Types = GetEntityTypes();
private static IEnumerable<Type> GetEntityTypes()
{
var assembly = Assembly.GetAssembly(typeof (IEntity));
var types = assembly.GetTypes().Where(t => String.Equals(t.Namespace, "Namespace", StringComparison.Ordinal));
return types;
}
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
if (!AllowType(objectType))
return new List<MemberInfo>();
var members = base.GetSerializableMembers(objectType);
members.RemoveAll(memberInfo => (IsMemberEntityWrapper(memberInfo)));
return members;
}
private static bool AllowType(Type objectType)
{
return Types.Contains(objectType) || Types.Contains(objectType.BaseType);
}
private static bool IsMemberEntityWrapper(MemberInfo memberInfo)
{
return memberInfo.Name == "_entityWrapper";
}
}
IEntity is an interface all my Code First entity objects implement.
I realise this question has an accepted answer, but I thought I would post my EF Code First solution for future viewers. I was able to get around the error message with the contract resolver below:
class ContractResolver : DefaultContractResolver
{
protected override List<System.Reflection.MemberInfo> GetSerializableMembers(Type objectType)
{
if (objectType.Namespace.StartsWith("System.Data.Entity.Dynamic"))
{
return base.GetSerializableMembers(objectType.BaseType);
}
return base.GetSerializableMembers(objectType);
}
}
This works because EF Code First classes inherit from the POCO class that you actually want serialized, so if we can identify when we are looking at an EF generated class (by checking the namespace) we are able to just serialize using the properties from the base class, and therefore only serialize the POCO properties that we were really after in the first place.
Well, you used powerful serialization API which serializes references and all members as well and now you complains that it serializes all members :)
I didn't test it but I believe this will bring you close to the solution.
JSON.NET is quite powerful tool and it should offer you the extensibility point to avoid this behavior but you will have to code it yourselves. You will need custom DataContractResolver where you define which members should be serialized. Here is the similar example for NHibernate.
You can implement some logic which will take only members present in the parent class of dynamic proxy. I hope this will not break lazy loading. To validate that current entity is proxy you can use this code to get all known proxy types:
IEnumerable<Type> types = ((IObjectContextAdapter)dbContext).ObjectContext.GetKnownProxyTypes();

How to work with navigation properties (/foreign keys) in ASP.NET MVC 3 and EF 4.1 code first

I started testing a "workflow" with EF code first.
First, I created class diagram. Designed few classes - you can see class diagram here
Then I used EF Code First, created EntsContext..
public class EntsContext : DbContext
{
public DbSet<Project> Projects { get; set; }
public DbSet<Phase> Phases { get; set; }
public DbSet<Iteration> Iterations { get; set; }
public DbSet<Task> Tasks { get; set; }
public DbSet<Member> Members { get; set; }
}
Next step was creating a ProjectController (ASP.NET MVC3) with simple action:
public ActionResult Index()
{
using (var db = new EntsContext())
{
return View(db.Projects.ToList());
}
}
The problem is: I am not getting a ProjectManager in view (List/Create scaffolding used). I would like to know if I am doing this wrong or scaffolding generation just ignores my properties, that aren't basic types.
Hmm... It is probably quite obvious.. because generator doesn't know what property of that Type should be used, right?
Well then I could modify my question a bit: What's a solid way to create a Project entity in this scenario (I want to choose a project manager during project creation)? Should I make a ViewModel for this?
ProjectManager will not be loaded by default. You must either use lazy loading or eager loading. Eager loading will load ProjectManager when you query Projects:
public ActionResult Index()
{
using (var db = new EntsContext())
{
return View(db.Projects.Include(p => p.ProjectManager).ToList());
}
}
Lazy loading will load ProjectManager once the property is accessed in the view. To allow lazy loading you must create all your navigation properties as virtual but in your current scenario it isn't good appraoch because:
Lazy loading requires opened context. You close context before view is rendered so you will get exception of disposed context.
Lazy loading in your case results in N+1 queries to DB where N is number of projects because each project's manager will be queried separately.
I believe you'll need a ProjectManager class, and your Project entity will need to have a property that points to the ProjectManager class.
Something like:
public class Project
{
public string Description {get; set;}
public Member ProjectManager {get; set;}
}

Resources