I've done this before, but not for some time and clearly I'm missing something.
In short, I've got a design-time model that inherits from my real view model and sets some properties in the constructor.
I'm importing the namespace in Xaml and IntelliSense is suggesting the desired class name, which leads me to believe my naming is error-free.
Even after a clean/build, I'm getting an error saying that the referenced model doesn't exist.
I can refer to the model from a .cs using Aurora.UI.ViewModels.SecurityViewModel_DesignTime without issue.
(In case it matters, this project has a target of x64. This is due to a dependency on an bit-dependent library. It's the only real difference I can point to when comparing to previous implementations).
The name "SecurityViewModel_DesignTime" does not exist in the namespace "clr-namespace:Aurora.UI.ViewModels"
And the model itself:
namespace Aurora.UI.ViewModels {
public class SecurityViewModel_DesignTime : SecurityViewModel {
public SecurityViewModel_DesignTime() {
this.Sensor = new Peripherals.Kinect();
this.PrimaryFeed = Kinect.Feed.Infrared;
Feeds = new List<Kinect.Feed> {Kinect.Feed.Infrared};
this.LookDirections =
Peripherals.Kinect.DirectionsRequired.Front |
Peripherals.Kinect.DirectionsRequired.Left |
Peripherals.Kinect.DirectionsRequired.Right |
Peripherals.Kinect.DirectionsRequired.Top;
}
}
}
(The class it's inheriting from is the 'real' viewModel and is a simple POCO)
What am I missing?
As per the comment, here's an answer:
Do a solution clean, and restart visual studio. Goodness knows why it works. The designer is janky at the best of times.
Related
I have a Working and Compileable WPF-Solution in a which I needed to copy to another directory.
Now I experience the following Problem, which I nowhere found similar on the web:
In some Projects every UserControl I created, isnt compileable anymore. Somehow Terms like DataContext or InitializeComponent() "do not exist in the current context".
Usually this is a case of wrong namespaces, or classnaming between the xaml and xaml.cs. As my code is all compileable in the original repo, this can not be the case. I've also checked that build action is set to Page, which is also a common issue in this case.
As I've found out, even newly created UserControls have the same problems. So I compared the projectfiles from the source and targed destination, which seemed to have no difference at all.
At this point I'll ask the community. Have you ever experienced a similar problem? What do you think i could check, too?
Thanks alot.
In my case there's been a reference inside my project which was wrong but that wasn't reported.
I solved my problem with readding all my references even if they were meant as correct.
Check the x:Class property on the pasted UserControl and make sure it matches the fully qualified class name of the codebehind
for instance in you have the following in MyUserControl.xaml.cs:
...
namespace MyApp
{
public partial class MyUserControl: UserControl
{
public MyUserControl()
{
InitializeComponent();
}
}
}
Then make sure the you have x:Class="MyApp.MyUserControl in your MyUserControl.xaml file
I seem to be running into a weird issue and after hours of head scratching, I seem to have narrowed the issue down to a combination of partial classes and virtual properties. When I override a property that's in a partial class, sitting in a separate file, MVC duplicates the fields on my view. I am using Visual Studio 2013 and the issue can be duplicated by following these steps:
Open Visual Studio and create a new Project. Choose Web under the categories, then choose "ASP.NET Web Application". I am targeting .NET 4.5.
Choose "Empty" from the template selection, then check the MVC checkbox so it adds the core folders and references.
Once the project is created, right-click on the Models folder and create a new class called MyModel.cs.
Add these lines to the new file:
public abstract partial class MyOriginalModel
{
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
public partial class MyModel : MyOriginalModel
{
}
Now right click on the Models folder again and create another new class called MyModelCustom.cs.
Add these lines to the file:
public partial class MyModel
{
[System.ComponentModel.DisplayName("First Name")]
[System.ComponentModel.DataAnnotations.Required]
public override string FirstName
{
get
{
return base.FirstName;
}
set
{
base.FirstName = value;
}
}
[System.ComponentModel.DisplayName("Last Name")]
[System.ComponentModel.DataAnnotations.Required]
public override string LastName
{
get
{
return base.LastName;
}
set
{
base.LastName = value;
}
}
}
Now build the project, then right click on the Controllers folder and add a new controller. Choose "MVC 5 Controller with read/write actions" and call it NamesController. Right click on the Create method and go to "Add View". Under the template dropdown, choose Create and for the Model Class dropdown, choose MyModel.
Once MVC creates the template, you will see that it adds First Name and Last Name twice. The issue seems to be related to partial classes because if I move the contents of MyModelCustom.cs into MyModel.cs, everything works fine. However, its not just partial classes. If I create a new property (versus overloading one) in the partial class, it does not duplicate that property. So it seems to be a combination of partial classes and overriding virtual properties.
Can someone please confirm if this is a bug or if I am doing something wrong?
It is a bit of both. Bug or not, if MVC is scaffolding incorrectly, you will either have to constantly fight the framework or change your approach to the problem.
As a general rule, I've found that when you have to fight the MVC framework to make it behave the way you want, then it is far easier to change your approach to the problem. Otherwise, you will end up fighting that particular battle repeatedly until you eventually comply. Take it from someone who's learned that lesson the hard way.
With easier approaches in mind, here are a few things you could try instead:
If you are overwriting a lot of properties, create separate classes with common names for properties (FirstName, LastName). Then use Best way to clone properties of disparate objects to marshall the data between objects.
You could also use Fody PropertyChange listeners to handle whatever logic is needed when these values are changed thereby eliminating the need for the partial overrides entirely.
A final option would be to override the scaffolding templates to skip overridden properties. Not sure how you would detect that though.
Take a look at CodePlex source for MvcScaffolding EnvDTETypeLocator.cs
/// <summary>
/// Out of a set of CodeType instances, some of them may be different partials of the same class.
/// This method filters down such a set so that you get only one partial per class.
/// </summary>
private static List<CodeType> PickArbitraryRepresentativeOfPartialClasses(IEnumerable<CodeType> codeTypes)
{
var representatives = new List<CodeType>();
foreach (var codeType in codeTypes) {
var codeClass2 = codeType as CodeClass2;
if (codeClass2 != null) {
var matchesExistingRepresentative = (from candidate in representatives.OfType<CodeClass2>()
let candidatePartials = candidate.PartialClasses.OfType<CodeClass2>()
where candidatePartials.Contains(codeClass2)
select candidate).Any();
if (!matchesExistingRepresentative)
representatives.Add(codeType);
} else {
// Can't have partials because it's not a CodeClass2, so it can't clash with others
representatives.Add(codeType);
}
}
return representatives;
}
}
:
:
1) PickArbitraryRepresentativeOfPartialClasses, the method uses Linq any() to confirm that the codeType as CodeClass2 has members.
CodeClass2 is the partial class type of EnvDTE, Visual Studio's core Automation library responsible for IDE code generation (Design Time Reflection).
2) If the class cast as CodeClass2 does have members, the class is added to the representatives
3) When the partial class is evaluated, each file will be visited within a distinct context (often leading to a consolidation of elements that should be overridden)
An interesting distinction between Run Time Reflection and Design Time Reflection: sic
An ASP.NET control has two distinct sets of functionality for when it is executed at run-time inside a page or used at design-time inside a host designer. Run-time capabilities determine, based on configuration, the markup that is output by the control. The design-time capabilities, instead, benefit of a visual designer such as Microsoft Visual Studio 2005. Design-time capabilities let the page author configure the control for run-time in a declarative and WYSIWYG (what-you-see-is-what-you-get) manner.
Conclusion:
MVC Scaffolding does use reflection, but it is the much less reliable Design Time Reflection.
Design Time Reflection is not the same as Run Time reflection. A fully compiled Class is a final result of inheritance resolves and partials combined and priority resolved. Design Time Reflection makes best guesses about how to work with complex, multi-part types.
If you want to rely on Scaffolding, better not to push it's limits. When you get errors like this, try simplifying your ViewModels:
Try consolidating your partial classes
Try removing your abstracts / virtuals
So I'm working on a practice project using Visual Studio 2012, MVC 4, and Entity Framework 5.0. I create an MVC 4 project using the "Basic" template. I add a simple Home/Index controller and view just to make sure everything is working. It is.
I add an edmx data model to my project under the models folder. (Connection strings are tested and good). I generate this model from a fairly simple SQL Express database. Here's some details about the model (generic names substituted):
Model edmx file structure looks like this in Solution Explorer:
[edmxFile] MyProjectModel.edmx
[SubFile] MyProjectModel.Context.cs
[Class] MyProjectEntities
[Method] MyProjectEntities()
[Method] OnModelCreating()
[Property] EntityAs: DbSet<EntityA>
[Property] EntityBs: DbSet<EntityB>
[Property] EntityCs: DbSet<EntityC>
etc...
[SubFile] MyProjectModel.Designer.cs
[SubFile] MyProjectModel.edmx.diagram
[SubFile] MyProjectModel.tt
[ClassFile] EntityA.cs
[ClassFile] EntityB.cs
[ClassFile] EntityC.cs
etc...
[ClassFile] MyProjectModel.cs
So I Rebuild my solution, then right click the "Controllers" folder and choose "Add"->"Controller" and choose the following options:
Controller name: "EntityAsController".
Scaffolding options:
Template: MVC controller with read/write actions and views, using Entity Framework
Model class: EntityA (MyProject.Models)
Data context class: MyProjectEntities (MyProject.Models)
Views: Razor (CSHTML)
Then I click "Add". I get the following error (again, generic names substituted):
'MyProject.Models.EntityA' is not part of the specified 'MyProject.Models.MyProjectEntities' class, and the 'MyProject.Models.MyProjectEntities' class could not be modified to add a 'DbSet<MyProject.Models.EntityA>' property to it. (For example, the 'MyProject.Models.MyProjectEntities' class might be in a compiled assembly.)
I originally got this error when I tried putting the edmx in a data layer project of its own and referencing that project from the main project. To solve,
I tried moving it to the main project. No luck.
I tried recreating the entire solution from scratch and creating it in the main project from the start. Same error.
I read and tried monkeying around with just about every solution or suggestion in this question/answer(s)/comment(s): Entity Framework MVC Controller no success.
I tried extending MyProjectEntities with a partial class and adding a wrapper property in order to FORCE it to have the desired "EntityA" property, like so:
public DbSet<EntityA> EntityA {
get { return this.EntityAs; }
set { this.EntityAs = value; }
}
All that did was give me an even more unhelpful error:
There was an error generating 'MyProject.Models.MyProjectEntities'. Try rebuilding your project.
I tried rebuilding the project. Same error.
Does anyone have any idea what's going on?
I found a solution to my own problem. It's a bit hacky, but it works.
The first error message above complains about "...class could not be modified to add a 'DbSet<MyProject.Models.EntityA>' property to it...". So I left my partial class for extending MyProject.Models.MyProjectEntities empty, like so:
public partial class MyProjectEntities : DbContext
{
}
Now, when I create the controller, MVC is of course still to stupid to see that the auto generated MyProjectEntities already contains the property it wants, BUT it now has a file for that class that it can modify to add a duplicate declaration of that property, modifying my code to look like this:
public partial class MyProjectEntities : DbContext
{
public DbSet<EntityA> EntityAs { get; set; }
}
It is happy, and makes my controller and views for me. Now, I just manually delete what it added to my code, so that there isn't an ambiguity error at build time. I build the project, start it, fire up my browser and go to "[siteUrl]/EntityAs", and TADA! It Works!
I hope that helps someone who has this problem. If anyone knows why MVC 4 and VS 2012 behave in this buggy way and require this hack solution, please comment or add another answer. It still bugs me a bit, and I'd love to hear more about it.
I'm having some problems finding a solution for this, though it seems straight-forward enough, and I imagine someone else must have run into this issue before.
Using MVC/Razor 4, I am trying to render a partial using a dynamic model.
To organize things, I have placed my partials in a sub-folder within the same view folder.
When the partial in question is moved to the sub-folder, it throws a RuntimeBinderException with an exception message saying that 'object' does not contain a definition for 'Id' (the parameter I am trying to access).
This works perfectly fine when the partial is located in the same folder.
This structure works fine
Views/Orders/Details.cshtml
Views/Orders/_PartialWithDynamicModel.cshtml
This structure causes the exception
Views/Orders/Details.cshtml
Views/Orders/MyPartials/_PartialWithDynamicModel.cshtml
CODE
Details.cshtml
#Html.Partial("MyPartials/_PartialWithDynamicModel", new { Id = 54 } )
_PartialWithDynamicModel.cshtml
#model dynamic
# { //The following line throws the RuntimeBinderException
int id = Model.Id; }
Any thoughts? If I move the partial into the same folder as the view, everything works fine.
Your problem is that you can't pass an anonymous type to an object in a separate assembly. They are created as "internal" types, and thus cannot be passed externally. Views are generated dynamically at runtime into their own assemblies.
Instead, use an ExpandoObject, like this:
#{ var myExpando = new ExpandoObject();
myExpando.Id = 54; }
#Html.Partial("MyPartials/_PutOnHoldForm", myExpando)
A better choice, however, would be to just pass a ViewDataDictionary, or perhaps use Tuples.
There is also the DynamicViewPage extension in the MVC futures project that allows you to do this as well without the expand object.
http://weblogs.asp.net/imranbaloch/using-the-features-of-asp-net-mvc-3-futures
(note, it says MVC3, but there is an MVC5 version of futures in Nuget)
I read Rick Strahl's article about ways to deal with the data context. My DBML is inside a class library, I keep my data context open by creating a static Current method in a separate custom partial class within library.
public partial class DataContext
{
public static DataContext Current
{
get
{
DataContext dc = HttpContext.Current.Items["dc"] as DataContext;
if (dc == null)
{
dc = new ImmediacyPageDataContext();
HttpContext.Current.Items["dc"] = dc;
}
return dc;
}
}
then access it like this
DataContext dc = DataContext.Current;
However, this causes issues whenever I update my DBML file. After editing the DBML file whenever I try and build the project my designer file doesn't regenerate/gets deleted. If I try running the custom tool option it comes back with an error.
The only way I can get round this is by renaming or deleting the custom partial class, re-generating the designer file, then adding my custom partial class back into the solution. This is a does work, but.. its a bit of a pain.
Is there a better approach to take that will make editing my DBML files easier, while prolonging my DC for as long as possible ?
Go into the code file with your partial DataContext class and move your using statements into your namespace. For some reason the tool will not generate the designer unless this is the case.
namespace MyNamespace
{
using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Xml.Linq;
partial class DataContext
{
}
}
I believe this change was required when moving from VS2008 to VS2008 SP1, though I may be mixing up some versions.
You should create your partial class in a different file, not the .designer.cs file. The easiest way to do this is to right-click on your DBML in the solution explorer (or in a blank area in the DBML designer) and click "View Code". This will create a new .cs file that won't be overwritten when you save your DBML.
I don't believe your DataContext persistence and DBML issue are related. It sounds like the IDE is confused versus a conflict with a Cached DataContext (HttpContext.Current.Items is per Request so there's no long-term caching anyway).
I had trouble with DBML compilation when my data model contained a class name that conflicted with another class. For instance, a DBML object named 'Application' (an insurance application) might conflict with HttpApplicationState.Page.Application.
Check your error message and see if it's specific to a name in your DBML.
I can't think of an overly compelling reason why your new static property must be part of the DataContext class. It would be just as easy to have it in a different class.