How to dynamically reflect changes to a Razor Page Model on pages and database? - visual-studio

I'm building my first Razor Pages app by following Microsoft's tutorial, and I'm curious about the correct way to reflect changes to my model on CRUD/scaffolded pages and corresponding database table. I have used below steps to handle this, but my solution feels more like a hack. Is there a better way to do it? I'm looking for a dynamic solution which allows for better separation of concerns.
What I aim to do: I want to remove CVRnr from below model, have the corresponding column in the database table dropped, as well as removing references to CVRnr on pages. The problem is that my changes to the model isn't reflected dynamically elsewhere in the project.
namespace Virksomhedsgodkendelser.Models
{
public class Company
{
public int ID { get; set; }
public int Pnr { get; set; }
public int CVRnr { get; set; }
}
}
What I have done to solve this:
Deleted public int CVRnr { get; set; } from the model
Deleted the CRUD pages in ~/Pages/Companies/
Re-added the CRUD pages via: Add > New Scaffolded Item > Razor Pages using Entity Framework
Deleted dbo.Company from my database
Re-added the database table via Package Manager Console: Add-Migration InitialCreate + Update-Database

Related

DbSet declaration does not accept the table name shown in database

I have developed an app for tracking multi-party coordination on proposed change requests.
I only use two table, with a one-to-one relationship. One table correlates to fields on an existing official paper form, while the other table tracks additional information in a one-to-one relationship.
I previously developed this app as a standalone project, using MS Access, but now, I am adding the app to a "one-stop shopping" SQL Server database environment.
My problem comes in my DbSet statements. The table names which the DBA chose result in errors which I never had when the app was stand-alone:
Below is the C# code for the DbContext portion:
namespace FormTracker
{
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<T__AODMS_1067_tracking_fields> T__AODMS_1067_tracking_fieldss { get; set; }
public DbSet<T__AODMS_1067_tracking_non_1067_fields> T__AODMS_1067_tracking_non_1067_fields_Recordss { get; set; }
}
}
The portions between the <> are what is being flagged when build is executed.
Any ideas? possibly something totally obvious that I'm not seeing?

NHibernate Many-To-Many Performance Issue

My application has the following entities (with a many-to-many relationship between Product and Model):
public class TopProduct {
public virtual int Id { get; set; }
public virtual Product Product { get; set; }
public virtual int Order { get; set; }
}
public class Product {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Model> Models { get; set; }
}
public class Model {
public virtual string ModelNumber { get; set; }
public virtual IList<Product> Products { get; set; }
}
Note: A product could have 1000s of models.
I need to display a list of TopProducts and the first 5 models (ordered alphabetically) against each one.
For example say I have the following query:
var topProducts = session.Query<TopProduct>()
.Cacheable()
.Fetch(tp => tp.Product).ThenFetchMany(p => p.Models)
.OrderBy(tp => tp.Order)
.ToList();
If I now say:
foreach (var topProduct in topProducts) {
var models = topProduct.Product.Models.Take(5).ToList();
...
}
This executes extremely slowly as it retrieves an item from the second level cache for each model. Since there could be 1000s of models against a product, it would need to retrieve 1000s of items from the cache the second time it is executed.
I have been racking my brain trying to think of a better way of doing this but so far I am out of ideas. Unfortunately my model and database cannot be modified at this stage.
I'd appreciate the help. Thanks
The key to your problem is understanding how entity and query caching work.
Entity caching stores, essentially, the POID of an entity and its property values.
When you want to get/initialize an instance, NH will first check the cache to see if the values are there, in order to avoid a db query.
Query caching, on the other hand, stores a query as the key (to simplify, let's say it's the command text and the parameter values), and a list of entity ids as the value (this is assuming your result is a list of entities, and not a projection)
When NH executes a cacheable query, it will see if the results are cached. If they are, it will load the proxies from those ids. Then, as you use them, it will initialize them one by one, either from the entity cache or from the db.
Collection cache is similar.
Usually, getting many second-level cache hits for those entity loads is a good thing. Unless, of course, you are using a distributed cache located in a separate machine, in which case this is almost as bad as getting them from the db.
If that is the case, I suggest you skip caching the query.

Key column not displayed despite ScaffoldColumn(true)

I'm working on ASP.NET MVC 3 project using EF CodeFirst. I have a simple class with few attributes set on key column:
public class Tag
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[ScaffoldColumn(true)]
public short TagID { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
}
As you can see there are DatabaseGenerated(DatabaseGeneratedOption.None) and ScaffoldColumn(true) attributes. That's because I want to be able to enter the TagID manually. Now when TagControler is added to the project I don't have the TagID column shown in neither of 5 generated views.
I know I can add it manually, but I wonder if this behavior is by design or I'm doing something wrong?
Primary keys aren't scaffolded as editable fields by default. Instead there is a hidden field for the key. If you wanted to change this behavior you could modify the templates but it is by design since generally it doesn't make sense to edit the primary key of an entity.
Here is some info on how to do this if you wanted to make this change any time you added a view or wanted to make some other custom change to the scaffolding:
http://blogs.msdn.com/b/joecar/archive/2011/01/06/add-the-asp-net-mvc-3-code-templates-to-your-application-with-nuget.aspx

Beginner EF4 / CodeFirst / MVC3 help

Although I love what I'm learning, I'm finding it a struggle and need some help
I've been using these two tutorials which I think are awesome:
http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx
http://msdn.microsoft.com/en-us/data/gg685467
Currently my main problem/confusion is:
I have a CodeFirst table/entity I don't know how to correctly get data from other tables/entities to show in my views:
public class Car {
public int ID { get; set; }
public string Name { get; set; }
public int EngineID { get; set; }
public virtual Engine { get; set; }
}
public class Engine {
public int ID { get; set; }
public string Name { get; set; }
public string Manufacturer { get; set; }
// (plus a whole lot of other things)
}
Now when I create a View for Cars (using the List type/option) I get a nice autogenerated list
#foreach (var item in Model) {
<tr>
<td>#item.ID</td>
<td>#item.Name</td>
<td>#item.EngineID</td>
</tr>
Perfect... except EngineID is mostly worthless to the viewer, and I want to show Engine.Name instead
So I assumed I could use EF lazy loading:
<td>#item.Engine.Name</td>
Unfortunately when I tried that, it says my ObjectContext has been disposed so can't get any further data requiring a connection
Then I tried going to the controller and including the Engine.Name
var cars = (from c in db.Cars.Include("Engine.Name") select c;
Which tells me: Entities.Engine does not declare a navigation property with the name 'Name'
... ? Lies
Include("Engine") works fine, but all I want is the Name, and Include("Engine") is loading a large amount of things I don't want
Previously in a situation like this I have created a view in the DB for Car that includes EngineName as well. But with CodeFirst and my noobness I haven't found a way to do this
How should I be resolving this issue?
I thought perhaps I could create a Model pretty much identical to the Car entity, but add Engine.Name to it. This would be nice as I could then reuse it in multiple places, but I am at a loss on how to populate it etc
Wanting to learn TDD as well but the above is already frustrating me :p
Ps any other tutorial links or handy things to read will be greatly appreciated
It isn't lies as you are actually trying to include a property that's a 2nd level down withouth giving it a way to navigate. If you let EF generate your DB with this structure, it would likely have made a navigation table called something like Car_Engine and if you include the name without the object it HAS mapped, then it's not got a navigation property in your new object.
The simple way around this is to go:
(from c in db.Cars.Include("Engine") select new { c, EngineName = c.Engine.Name }
If you still get navigation property errors then you might need to make sure your are mapping to your schema correctly. This can be done with EntityTypeConfiguration classes using the fluent API - very powerful.
This of course won't help in strongly typing your car object to show in MVC.
If you'd like to get around this, your gut feeling is right. It's pretty common to use viewmodels that are read only (by design, not necessarily set to readonly) classes that provide simple views of your data.
Personally I keep my model quite clean and then have another project with viewmodels and a presentation project to populate. I'd avoid using overlapping entities in your core model as it might lead to unpredictable behaviour in the data context and at least a peristance nightmare when updating multiple entities (ie who's responsible for updating the engine name?).
Using you viewmodels, you can have a class called CarSummaryView or something with only the data you want on it. This also solves the issue of being vulnerable to overposting or underposting on your site. It can be populated by the above query quite easily.
PS There's a bunch of advantages to using viewmodels beyond just not loading full heirarchies. One of the biggest is the intrinsic benefit it gives you with avoiding over and underposting scenarios.
There's loads of ways to implement viewmodels, but as a simple CarView example:
public class CarView
{
public int ID { get; set; }
public string Name { get; set; }
public string EngineName { get; set; }
}
This should be clearly seperated from your entity model. In a big project, you'd have a single viewmodels project that the presenter can return, but in a smaller one you just need them in the same layer as the service code.
To populate it directly from the query, you can do the following
List<CarView> cars = (from c in db.Cars.Include("Engine.Name") select new CarView() { ID = c.ID, Name = c.Name, EngineName = c.Engine.Name }).ToList();

Using the entity modal with mvc -mvvm

Hi there I am hoping someone can point me in the right direction.
I want to create an mvc applicaton I have worked my way through the music store example and still am not 100% sure the correct way to do things.
Lets say I want to create an application that stores cooking receipes.
I have a 3 tables
RecipeTable
RecipeID
RecipeName
RecipeIngredients
RecipeIngredientID
RecipeID
IngredientID
Measurement
IngredientTable
IngredientID
IngredientName
All have PK & FK mappings very basic, I create a new mvc application and use the entity framework to create a new entity e.g. RecipeDB
My next step is I create a new model for each of the tables and give the properties my desired displaynames and specify required fields extra.
Do I then create a viewmodel e.g. RecipesViewModel that looks something like
public class RecipesViewModel
{
public int RecipeID { get; set; }
public string RecipeName { get; set; }
public List<RecipeIngredients> { get; set; }
}
I now create the controller (Ithink) but I am not really sure how to bind that to database entity.
I know you can call the database by doing something like RecipeEntities db = new recipeEntites(); however binding the results to the vm I am little confussed on how to do that.
Am I heading in the right direction so far?
You could use AutoMapper. It's a great tool allowing you to convert from one type to another and in your case from the model to the view model.
public ActionResult Foo()
{
RecipeDB model = _repository.GetRecipies();
RecipesViewModel viewModel = Mapper.Map<RecipeDB, RecipesViewModel>(model);
return View(viewModel);
}
or you could even define a custom action attribute (like the one I used in my sample MVC project) allowing you to simply write:
[AutoMap(typeof(RecipeDB), typeof(RecipesViewModel))]
public ActionResult Foo()
{
RecipeDB model = _repository.GetRecipies();
return View(model);
}

Resources