I have looked at two of Microsoft's tutorials for MVC. In one tutorial they are creating a .edmx file to handle the Entity Framework in order to execute Linq queries. In another tutorial they made a class called "MusicStoreEntities.cs" here is the code:
using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Cart> Carts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
}
And the tutorial creates an instance of this class and starts doing Linq queries as well. What are the differences between these 2 methods? and how can I make DbSet objects in a .edmx file? Thank you.
There are various ways to create your model structure.
You can code POCO classes first, and create the database manually.
You can code POCO classes first, and create the database automatically using code first libraries.
You can create your database schema, and import it into a class diagram (which will supply all the models and navigation).
You can create your class diagram, and create your database schema from that.
1 and 2 create only the cs, while 3 and 4 create the edmx.
You can check this for Code First EF (this includes the DbSet part of your question).
EDIT: You can even use POCO classes with an existing database, as posted here.
Related
My team uses Db first design.
We create the database, then create the model using the Scaffold-DbContext command.
The problem is when we need to modify the model and then do a recreation.
public partial class UserInfo
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime RecordCreated { get; set; }
}
Upon invoking a Scaffold-DbContext with the -Force it will remove the [Required] from it.
Should I be looking at using a ViewModel, creating partial classes or what?
Very early on in using EF core 2.1 so any help would be greatly appreciated.
Joe
If you are using database first, you make the database column required (NOT NULL), and then run scaffolding again, not the other way round. When scaffolding, you can choose to generated Attributes over fluent configuration, if you do that, you will get the "Required" attribute added (for reference types).
The switch for Scaffold-Dbontext is -DataAnnotations
https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/powershell#scaffold-dbcontext
Use EF Core Power Tools, it generates a partial method for OnModelCreating, and then use the fluent API in a new partial class to set the Required option instead of attributes.
I understand that it was created DB first but after initial creation of the models if you do model changes before changes in db it would be best to create migrations from code that way all the changes to the models will be replicated in the database.
As pointed out by ErikEJ this won't work:
You could use a metadata class along with a partial class (example
copied from doc):
using System;
using System.Web.DynamicData;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
[MetadataType(typeof(UserInfoMetaData))]
public partial class UserInfo
{
}
public class UserInfoMetaData
{
[Required()]
public object FirstName;
}
This would then sit in a separate file, that won't be touched by
code-gen. Note that you don't need to add all properties to the
metadata class and their type doesn't matter - but the names must
match.
There are some ways however how to make it work, see this SO item which itself is based on this ASP.NET Forums question. In the ASP.net link, there is also a suggestion to make the validation on the view model instead of the data classes. So that might be a possibility to consider.
I am working on an asp.net mvc-4 web application and i am using Entity Framework 5.0 . now i have mapped my sql server 2008 tables using entity framework with database first approach. but i got this strange issue after completing the mapping, now inside my database i have a table named ""People as follow:-
but on the generated edmx file the table was renamed as "Person" , here is how the entity looks like inside my edmx file :-
here is the generated model class:-
using System;
using System.Collections.Generic;
public partial class Person
{
public long CIID { get; set; }
public string ATTRIBUTE_1202 { get; set; }
public virtual BaseElement BaseElement { get; set; }
public virtual Requester Requester { get; set; }
public virtual Technician Technician { get; set; }
}
}
so can anyone adivce why the "People" table is presented as an Entity named "Person" inside the .edmx file ?
I think, you checked option "Pluralize or aingularize generated object names".
So People means many, Person means single.
Usually, it just adds or removes s and es in the end, but in some cases it does more complex replacements.
I'm using EF5 to produce a model from an existing DB structure. I map Insert/Update/Delete Stored Procedures to the entities. This is working fine.
What I would like to do next is pass a UserId to these SPs as a parameter but not have the UserId as a column within the underlying table (the SPs will utilize this parameter). I have lots of entities. Is it possible to somehow add a property that will always be added back in even after updating the model from the DB?
Many Thanks
If you are using EDMX to generate the Entity Framework object model, your classes are partial and you can add properties to the partial classes of your entities which will survive database regeneration.
If you have a ParticularEntity table in the DB and referenced in the EDMX, you may add a partial class file ParticularEntity.Augments.cs (the name is for your reference, and you can have multiples as normal with partial classes) to your project and within it
public partial class ParticularEntity
{
public string UserId { get; set; }
public void DoSomething(string userId)
{
someFunctionThatYouWantToNotBeAnExtension();
}
}
Alternatively, you could write a set of extension methods which your maps utilize. I don't think that's as clean as extending the EF classes with partials, though.
Entity created by EF are partial class so you can extend that class with your custom properties
YourEntity.cs //created by EF
public partial class YourEntity
{
public string Name { get; set; }
...
}
YourEntityExtended.cs // created by you
public partial class YourEntity
{
public int Id { get; set; }
}
My problem lies in the lack of experience in MVC. Basically, I have two tables in DB
-Person
-Offer
For each I have created a model and a controller and a model, so the structure looks like that:
public class Offer
{
public int OfferID { get; set; }
public string OfferTitle { get; set; }
public string State { get; set; }
public string Description { get; set; }
}
public class OfferDBContext : DbContext
{
public DbSet<Offer> Offers { get; set; }
}
This is the Offer model.
public class Person
{
public int PersonID { get; set; }
public string Username { get; set; }
public DateTime Birthday { get; set; }
public string Education { get; set; }
public string Email { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> Persons { get; set; }
}
This is the Person model.
Firstly I created the Person model, that added itself to db without any problems. Then I wanted to add Offer table, and I had to use the DropCreateDatabaseIfModelChanges method. I used it for OfferInitializer and PersonInitializer and then there is the Global.asax.cs file
protected void Application_Start()
{
Database.SetInitializer<OfferDBContext>(new OfferInitializer());
Database.SetInitializer<PersonDBContext>(new PersonInitializer());
//Database.SetInitializer<PersonDBContext>(new PersonInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
From what I understand, I cant do that simply because I am dropping database 2 times, each time populating only one table at a time. How do I reorganize it all, so that I can populate both or more tables at a time, or the whole database?
First things first, you should not create individual DbContext classes for each table. You should instead put all your DbSets in the same DbContext. Doing this will simplify things greatly for you.
Secondly, you should look into using migrations. You should start using them very early in your project.
You work with code first migrations using the Package Management Console.
enable-migrations
Does exactly what the name implies. Initializes migrations in your project. This will create a folder inside your project and generate the files needed.
add-migration InitialCreate
This creates a migration. InitialCreate is actually a string and you can change it to whatever you want. This command will generate the scripts needed to create the database from strach.
update-database
This command verifies the database and applies the migration (or migrations - there can be multiple) required in order to get the database up-to-date.
This is the initial setup. If you do further changes to your first code first classes, or add more, you will just have to add a new migration and then execute it.
add-migration AddedFirstName
update-database
It's that simple!
There are some more advanced concepts like seed, rollback, update to specific migration, etc., but what I have typed above covers the basics and the day to day usage of migrations.
I recommend you to read this article which explains everything in much more detail: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application
Im creating a class library that will be used in several projects. This library includes a handfull of entities with associated tables in the database. My question is: how do I create these tables when I include this library in a project?
I suspect you want a library of objects that are used to generate a database?
If so you can achieve this with EntityFramework CodeFirst.
At minimum you'll need your objects and a DbContext.
a typical set up maybe as follows:
Entities
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
DbContext
public class MyDbContext : System.Data.Entity.DbContext {
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
public DbSet<Person> People { get; set; }
}
These would live in your project and when you add a reference to it, for example a web project. There are different ways to build the Database, you could call the constructor (MyDbContext) from your web project and pass a connection string to a server.