ASP.Net MVC with Entity Framework Code First Navigation Property - c#

I have an entity called Service like following:
public class Service
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int serviceId { get; set; }
public string name { get; set; }
public string description { get; set; }
public ServiceCategory category { get; set; }
}
The category is chosen by the user through a drop down that holds the id and the name of the categories available in the db. the ViewModel will then return that id to me to save. The way I've been doing this so far is by going to my repository, getting the category object where the id matches the selected category in the view and then assigning it. This of course takes a round trip to the db.
I was wondering, since I already have the id, is there a better way of doing this where I don't go to the db?

modify your code to
public class Service
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int serviceId { get; set; }
public int ServiceCategoryId {get; set;} // Added
public string name { get; set; }
public string description { get; set; }
public ServiceCategory ServiceCategory { get; set; }
}
and fill ServiceCategoryId.

Related

Invalid ForeignKeyAttribute name with Entity Framework in code first approach

I have the following models
public class Team
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("User")]
public int ManagerId { get; set; }
public virtual User User { get; set; }
}
Here is my User class:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[ForeignKey("Comapny")]
public int CompanyId { get; set; }
public virtual Company Company { get; set; }
}
Here is my Company class:
public class Company
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
}
When I try to add a new migration I get the following error
The ForeignKeyAttribute on property 'CompanyId' on type
'ReportsEngine.Areas.Test.Models.User' is not valid. The navigation
property 'Comapny' was not found on the dependent type
'ReportsEngine.Areas.Test.Models.User'. The Name value should be a
valid navigation property name.
What am I doing wrong here?
Its just a typo, Company instead of Comapany
[ForeignKey("Company")]
public int CompanyId { get; set; }
[ForeignKey("Comapny")] indicates that the property to use for the foreign key to the Company table should be Comapny.
The error is because you have not defined a Comapny property on the Company table.
Add the following to the Company table:
public int Comapny { get; set; }
Obviously it may be better to prefix it with Id just to show it is that type of field.
Or you could omit the [ForeignKey] attribute to let Entity Framework code first add one for you.

asp.net: How do I combine two models together to be able to create a Parent and all of its child entities?

I am new to use ASP.net and MVC and in need of some help.I am currently working on a project which is an online recipe book, and I have various tables but the two tables I want to combine into one view is Recipe and RecipeIngredients, as shown below:
Recipe.cs
namespace TheOnlineFoodBook.Models
{
public class Recipe
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RecipeID { get; set; }
[Display(Name = "Recipe")]
public string RecipeName { get; set; }
[Display(Name= "Cuisine")]
public int CuisineID { get; set; }
public string Directions { get; set; }
[Display(Name = "Preperation Time:")]
public double PreperationTime { get; set; }
[Display(Name = "Cooking Time:")]
public double CookingTime { get; set; }
public virtual List<RecipeIngredient> RecipeIngredients { get; set; }
[ForeignKey("CuisineID")]
public virtual Cuisine Cuisine { get; set; }
}
}
RecipeIngredient.cs
public class RecipeIngredient
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int RecipeID { get; set; }
public int IngredientID { get; set; }
public double Quantity { get; set; }
public int MeasurementID { get; set; }
public string Notes { get; set; }
public virtual Recipe Recipe { get; set; }
public virtual Measurement Measurement { get; set; }
public virtual Ingredient Ingredient { get; set; }
}
}
I've read a little about combining models to create a viewModel but i'm not sure how I would go about doing this, and I also want to be able to add multiple RecipeIngredients entries at the same time when creating a Recipe. Currently I have the basic CRUD views working which entity framework created for me.
You already have a "Recipe" object in "RecipeIngredient" so using "RecipeIngredient" as model in your view would give you access to "Recipe" properties, another approach you could take is using #modelTuple<Recipe,RecipeIngredient> in your view after passing new Tuple<Person, Order>(new Recipe(),new RecipeIngredient()); as you would pass a model, but I wouldn't see the use in following the later one since "RecipeIngredient" already has "Recipe"
Will this do what you need?
public class RecipeViewModel
{
public Recipe Recipe { get; set; }
public List<RecipeIngredients> RecipeIngredientsList { get; set; }
}
You won't be able to use data annotations as effectively, but if that isn't a concern you will now be able to attach multiple RecipeIngredients to the same Recipe for your page.

Key Already Exists in Table when Scaffolding

I am doing a code first example, and basically I have Products and Categories.
The Category Model is as follows :
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
and the Product model is as follows:
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
public decimal Price { get; set; }
[Required]
public int Stock { get; set; }
public string ImageName { get; set; }
//Category Navigation
public int CategoryId { get; set; }
public Category Category { get; set; }
}
When I try to create a Controller with the Web API 2 Controller with actions, using Entity Framework scaffold, I am getting an error :
There was an error running the selected code generator : 'Key already
exists in table'
I am suspecting its the Category Navigation part of the Product Model since without that code, the scaffold works.
What am I doing wrong? I tried to create it as a virtual property but I am still getting the same error.
You need to add the Model classes in your DbContext
public DbSet<Product> Products{ get; set; }
public DbSet<Category> Categories{ get; set; }
Now you could do the scaffolding.
This question will also help for a better understanding

Creating a controller for a model using EF (No key error)

I'm trying to create a controller with scaffolding based on the following model (with no previously created context, but I chose the option to create it alongside the controller):
namespace MvcMusicStorePractice.Models
{
public class Album
{
public virtual int AlbumId { get; set; }
public virtual int GenreId { get; set; }
public virtual int ArtistId { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
}
But I keep getting the following error:
Album::EntityType 'Album' has no key defined. Define the key for this EntityType.
I'v tried the following solutions:
Adding the [Key] attribute to the AlbumId;
Changing the public virtual int AlbumId to simply public int Id.
It still does not work however. Does anyone know what the problem is?
In order to use the entity framework, every entity needs a key. This is how EF tracks objects in its cache, posts updates back to the underlying data store, and links related objects together:
namespace MvcMusicStorePractice.Models
{
public class Album
{
[Key]
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
}
Mind the [key] annotation that will make that field the PK.
Also make sure to only use "Virtual" with foreign objects (Only Genre & Artist)/

Entity framework code first, shopping cart

I am new to entity framework, I was trying to implement a simple shopping cart using code first approach, and I didnt understand why entity generates the table in strange way below. Here is the cut down version of my classes:
Product.cs
public class Product
{
[Key]
public int ID { get; set; }
public int ProductCategoryID { get; set; }
public string ProductNumber { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Specification { get; set; }
public string Color { get; set; }
public string Capacity { get; set; }
public string CapacityUnitMeasureCode { get; set; }
public decimal Price { get; set; }
public decimal Cost { get; set; }
public int Stock { get; set; }
}
ShoppingCart.cs
public class ShoppingCart
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
public int Quantity { get; set; }
public DateTime CreatedDate { get; set; }
public virtual List<Product> products { get; set; }
}
Because of this line
public virtual List products { get; set; }
Entity generates the Product table with 2 additional foreign keys:
ShoppingCart_ID & ShoppingCart_ProductID
Which I dont understand. my intention was to create a List of product that associated to a particular shopping cart. What I am I doing wrong. Could someone shed some light please!
SInce you have ProductID as one of the property in shopping cart class and you have virtual product collection in shopping cart, EF has established relationship between shopping cart and product class.
as suggested in comment you can remove product id class or you can create a view model class and establish relation ship between shopping cart and product class.
Sample View model can be
public class ShoppingCartProduct
{
[Key]
[Column (Order=1)]
public int ID { get; set; }
[Key]
[Column(Order = 2)]
public int ProductID { get; set; }
}
you can read about view model here
http://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CB4QFjAA&url=http%3A%2F%2Frachelappel.com%2Fuse-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications&ei=EP20VNqDHcTkuQTqvYGoAw&usg=AFQjCNHdOjOFhZGuBiLHZJ0wBGsG9qQtXw&sig2=rSFNWzWstWP0z0yRDhuXXQ
The great solution for you is to make a class ShopingCart wich contain all your products and their number:
[Table("Cart")]
public class ShopingCart
{
[Key]
public int Id { get; set; }
public DateTime CreatedDate { get; set; }
public virtual ICollection<ItemCart> Products { get; set; } // relationship one-to-many
}
And the class wich contains your ItemCart
[Table("ItemCart")]
public class ItemCart
{
[Key]
public int Id { get; set; }
public int Quantity { get; set; }
public virtual Product Product { get; set; } // relationship one-to-one
}
If you want to learn more look on this page: entity-tutorial
And try to make think simple: You have just 3 possible relationships:
one-to-one
one-to-many
many-to-many but here is creating an intermittent table link
Hope to be useful for you!

Categories

Resources