I am following along to this tutorial on EF6 and Codefirst. http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
I started a solution and just added the Models, the contexts and the initializer
namespace TestContoso.DAL
{
public class SchoolContext : DbContext
{
public SchoolContext()
: base("Name=SchoolContextDB")
{
}
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
and created a dummy Home Controller and Index view.
namespace TestContoso.Controllers
{
public class HomeController : Controller
{
private SchoolContext db = new SchoolContext();
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
}
}
I have also set the Connection String and set the initializer in web.config
<entityFramework>
<contexts>
<context type="TestContoso.DAL.SchoolContext, TestContoso">
<databaseInitializer type="TestContoso.DAL.SchoolInit, TestContoso"/>
</context>
</contexts>
When I run the solution, my expectation is that the database would get created, however I notice that the OnModelCreating event never fires so the db is never created. Why isn't the db getting created? How would I cause the Code First migration to fire?
The article gives you an alternative. Try the alternative method of adding the initialization strategy via code to see if that works.
As an alternative to setting the initializer in the Web.config file is to do it in code by adding a Database.SetInitializer statement to the Application_Start method in in the Global.asax.cs file.
Database.SetInitializer(new CreateDatabaseIfNotExists<SchoolContext>());
And as specified in the comments. Run a query against the data or follow the section on 'Set up EF to initialize the database with test data' to automatically seed the database.
The OnModelCreating event only seemed to get fired when there was some query querying that model, to test that I just added a dummy query in the Index controller and it worked.
public class HomeController : Controller
{
private SchoolContext db = new SchoolContext();
//
// GET: /Home/
public ActionResult Index()
{
var students = from s in db.Students
select s;
return View();
}
}
}
Related
I am using .Net Core 2.1 and EF Core 2.1. I successfully created 2 tables with EF Code First Migrations and dotnet CLI also seeded data into it. However when I try to add a new model Feature, and run the migration, the file generated has empty Up() and Down() methods and there is no entry in the EF_MigrationsHistory table of Database and the modelSnapshot.cs file also doesn't contain any references to the Feature model. I cross checked the ApplicationDbContext to see if I accidentally missed the declaration of the model in the class but I hadn't. I am not sure of the issue. Can anyone help me out with this? Posting the codes from my project:
Feature.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace ProjectName.Models
{
public class Feature
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
}
}
ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using ProjectName.Models;
namespace ProjectName.Persitance{
public class ApplicationDbContext: DbContext{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context)
: base(context){ }
public DbSet<Make> Makes { get; set; }
public DbSet<Feature> Features { get; set; }
}
}
20180906063933_AddFeature.cs(Migration File):
using Microsoft.EntityFrameworkCore.Migrations;
namespace ProjectName.Migrations
{
public partial class AddFeature : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
ApplicationDbContextModelSnapshot.cs:
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Application.Persitance;
namespace Application.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.2-rtm-30932")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy",
SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Application.Models.Make", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy",
SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.ToTable("Makes");
});
modelBuilder.Entity("Application.Models.Model", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy",
SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("MakeId");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(255);
b.HasKey("Id");
b.HasIndex("MakeId");
b.ToTable("Models");
});
modelBuilder.Entity("Application.Models.Model", b =>
{
b.HasOne("Application.Models.Make", "Make")
.WithMany("Models")
.HasForeignKey("MakeId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
__EFMigrationsHistory DB Image:
Usually this happens when you include context.Database.EnsureCreated(); in your seed data file. This method doesn't allow to create a migrations table and cannot be used with migrations. You need to remove migrations with Remove-Migration command or delete the Migration folder and the database in your server and create new migration. Check Microsoft docs for better understanding.
I was having a similar issue. The Up method was empty despite cleaning the migrations folder and running dotnet ef migrations add Initial multiple times.
The solution in my case was to change the DbSet properties and add virtual to each of them.
Instead of
public DbSet<Make> Makes { get; set; }
try
public virtual DbSet<Make> Makes { get; set; }
We have ASP MVC web project. After reading a lot of articles and discussions here in stackoverflow about the correct architechture we have decided to go with the following one, although there is not only one correct way of doing things this is the way we have decided, but we still have some doubts.
We are publishing this here not only to be helped but also to show what we have done in case it is helpful to somebody.
We are working in ASP .NET MVC project, EF6 Code first with MS SQL Server.
We have divided the project into 3 main layers that we have separate into 3 projects: model, service and web.
The model creates the entities and setup the DataContext for the database.
The service make the queries to the data base and transform those entities into DTOs to pass them to the web layer, so the web layer doesn't know anything about the database.
The web uses AutoFac for the DI (dependency Injection) to call the services we have in the service layer and obtain the DTOs to transform those DTOs into Model Views to use them in the Views.
After reading a lot of articles we decided not to implement a repository pattern and unit of work because, in summary, we have read the EF acts as a unit of work itself. So we are simplifying things a little here.
https://cockneycoder.wordpress.com/2013/04/07/why-entity-framework-renders-the-repository-pattern-obsolete/
This is the summary of our project. Now I'm going to go through every project to show the code. We are going to show only a couple of entities, but our project has more than 100 different entities.
MODEL
Data Context
public interface IMyContext
{
IDbSet<Language> Links { get; set; }
IDbSet<Resources> News { get; set; }
...
DbSet<TEntity> Set<TEntity>() where TEntity : class;
DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
}
public class MyDataContext : DbContext, IMyContext
{
public MyDataContext() : base("connectionStringName")
{
}
public IDbSet<Language> Links { get; set; }
public IDbSet<Resources> News { get; set; }
...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));
}
}
Here is how we declare the entities
public class Link
{
public int Id{ get; set; }
public string Title { get; set; }
public string Url { get; set; }
public bool Active { get; set; }
}
SERVICES
These are the generic classes we use for all the services.
As you see we use the DTOs to get data from the web layer. Also we connect to the database using Dbset = Context.Set()
public interface IService
{
}
public interface IEntityService<TDto> : IService where TDto : class
{
IEnumerable<TDto> GetAll();
void Create(TDto entity);
void Update(TDto entity);
void Delete(TDto entity);
void Add(TDto entity);
void Entry(TDto existingEntity, object updatedEntity);
void Save();
}
public abstract class EntityService<T, TDto> : IEntityService<TDto> where T : class where TDto : class
{
protected IClientContext Context;
protected IDbSet<T> Dbset;
protected EntityService(IClientContext context) { Context = context; Dbset = Context.Set<T>(); }
public virtual IEnumerable<TDto> GetAll()
{
return Mapper.Map<IEnumerable<TDto>>(Dbset.AsEnumerable());
}
public virtual void Create(TDto entity)
{
if (entity == null)
{
throw new ArgumentNullException(nameof(entity));
}
Dbset.Add(Mapper.Map<T>(entity));
Context.SaveChanges();
}
public virtual void Update(TDto entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
Context.Entry(entity).State = EntityState.Modified;
Context.SaveChanges();
}
public virtual void Delete(TDto entity)
{
if (entity == null) throw new ArgumentNullException(nameof(entity));
Dbset.Remove(Mapper.Map<T>(entity));
Context.SaveChanges();
}
public virtual void Add(TDto entity)
{
Dbset.Add(Mapper.Map<T>(entity));
}
public virtual void Entry(TDto existingEntity, object updatedEntity)
{
Context.Entry(existingEntity).CurrentValues.SetValues(updatedEntity);
}
public virtual void Save()
{
Context.SaveChanges();
}
}
We declare the DTOs in this project (this is a very simple example so we don't have to put all the code here):
public class LinkDto
{
public int Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public bool Active { get; set; }
}
Then one of our services:
public interface ILinkService : IEntityService<LinkDto>
{
IPagedList<LinkDto> GetAllLinks(string searchTitle = "", bool searchActive = false, int pageNumber = 1, int pageSize = 10);
LinkDto FindById(int id);
LinkDto Test();
}
public class LinkService : EntityService<Link, LinkDto>, ILinkService
{
public LinkService(IClientContext context) : base(context) { Dbset = context.Set<Link>(); }
public virtual IPagedList<LinkDto> GetAllLinks(bool searchActive = false, int pageNumber = 1, int pageSize = 10)
{
var links = Dbset.Where(p => p.Active).ToPagedList(pageNumber, pageSize);
return links.ToMappedPagedList<Link, LinkDto>();
}
public virtual LinkDto FindById(int id)
{
var link = Dbset.FirstOrDefault(p => p.Id == id);
return Mapper.Map<LinkDto>(link);
}
public LinkDto Test()
{
var list = (from l in Context.Links
from o in Context.Other.Where(p => p.LinkId == l.Id)
select new OtherDto
{ l.Id, l.Title, l.Url, o.Other1... }).ToList();
return list;
}
}
As you see we use AutoMapper (version 5 which has changed a little) to transform from Entities to DTOs the data.
One of the doubts we have is if the use of "Dbset.Find" or "Dbset.FirstOrDefault" is correct and also if the use of "Context.Links" (for any entity).
WEB
FInally the web project where we receive the DTOs and transform those DTOs into ModelViews to show in our views.
We need to call, in the Global.asax Application_Start, AutoFac to do the DI so we can use our services.
protected void Application_Start()
{
...
Dependencies.RegisterDependencies();
AutoMapperBootstrapper.Configuration();
...
}
public class Dependencies
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
builder.RegisterModule(new ServiceModule());
builder.RegisterModule(new EfModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
public class ServiceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.Load("MyProject.Service")).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
}
}
public class EfModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType(typeof(MyDataContext)).As(typeof(IMyContext)).InstancePerLifetimeScope();
}
}
As you see we also call AutoMapper to configure the different maps.
Then in our controllers we have this.
public class LinksController : Controller
{
private readonly ILinkService _linkService;
public LinksController(ILinkService linkService)
{
_linkService = linkService;
}
public ActionResult Index()
{
var links = _linkService.GetAllLinks();
return View(links.ToMappedPagedList<LinkDto, LinksListModelAdmin>());
}
...
public ActionResult Create(LinksEditModelAdmin insertedModel)
{
try
{
if (!ModelState.IsValid) return View("Create", insertedModel);
var insertedEntity = Mapper.Map<LinkDto>(insertedModel);
_linkService.Create(insertedEntity);
return RedirectToAction("Index");
}
catch (Exception ex)
{
throw ex;
}
}
}
Well, this is it...I hope this can be useful for somebody...and also I hope we can have a little help with the questions we have.
1) Although we are separating database from the web project we do need a reference in the web project to initialize the database and also to inject dependencies, is this correct?
2) Is it correct the approach we have done having our Entities->DTOs->ViewModels? It's a little more work but we have everything separated.
3) In the Service project, when we need to reference a different entity than the main one we are using in the service, is it correct to call Context.Entity?
For example, if we need to retrieve also data from the News entity in the links service, is it correct to call "Context.News.Where..."?
4) We do have a little problem with Automapper and EF proxy, because when we call "Dbset" to retrieve data, it gets a "Dynamic proxies" object so Automapper can't find the proper map so, in order to work, we have to set ProxyCreationEnabled = false in the DataContext definition. This way we can get an Entity in order to map it to the DTO. This disables LazyLoading, which we don't mind, but is this a correct approach or there is a better way to solve this?
Thanks in advance for your comments.
For Question no. 2
Entities->DTOs->ViewModels? is good approach
because you are doing the clean separation, the programmer can work together with ease.
The person who design ViewModels, Views and Controllers don't have to worry about the service layer or the DTO implementation because he will make the mapping when the others developpers finish their implementation.
For Question no. 4
When the flag ProxyCreationEnabled is set to false, the proxy instance will not be created with creating a new instance of an entity. This might not be a problem but we can create a proxy instance using the Create method of DbSet.
using (var Context = new MydbEntities())
{
var student = Context.StudentMasters.Create();
}
The Create method has an overloaded version that accepts a generic type. This can be used to create an instance of a derived type.
using (var Context = new MydbEntities())
{
var student = Context.StudentMasters.Create<Student>();
}
The Create method just creates the instance of the entity type if the proxy type for the entity would have no value (it is nothing to do with a proxy). The Create method does not add or attach the entity with the context object.
Also i read some where if you set ProxyCreationEnabled = false the child element will not loaded for some parent object unless Include method is called on parent object.
Entity Framework Core is not returning any results. I've been searching near and far. I find some tutorials saying one thing and others saying another. Here is what I have so far:
Buyer.cs
[Table("DealerCustomer", Schema = "dbo")]
public class Buyer
{
[Key]
public int DealerCustomerKey { get; set; }
public int DealerId { get; set; }
}
BuyerContext.cs
public class BuyerContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("db connection string here");
}
public DbSet<Buyer> Buyers { get; set; }
}
Startup.cs > ConfigureServices function
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<BuyerContext>(options =>
options.UseSqlServer("db connection string here");
services.AddMvc();
}
Now I am trying to load the Buyers data from my BuyerController.cs:
[Route("api/[controller]")]
public class BuyersController : Controller
{
private BuyerContext _context;
public BuyersController(BuyerContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<Buyer> Get()
{
System.Diagnostics.Debug.WriteLine("getting buyers");
System.Diagnostics.Debug.WriteLine(_context.Buyers);
return _context.Buyers;
}
}
This is all returning empty brackets when I load the page, instead of a list of Buyers. However there are over 1000 rows in that table (dbo.DealerCustomer). I know I have two places adding the db connection string but tutorials kept show both ways of doing it and when I only did it in startup.cs I was getting errors about the _context. I can make everything look pretty later, right now I just want a good connection so I have a starting place to work from.
I found there was a timeout because one of the decimal fields was returning null.
EF Core Timing out on null response
I have two projects each with their own DbContext class that write to the same SQL Server 2012 database.
The DbContext classes are of the form:
public class BlogDbContext : DbContext
{
public BlogDbContext()
: base("CodeFirstTestConnString")
{
}
public BlogDbContext(string connectionString)
: base(connectionString)
{
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//modelBuilder.HasDefaultSchema("blogtest");
}
}
Using Code First Migrations I can create my tables in the (existing) database by executing the following in each project:
Enable-Migrations
Add-Migration Initial
Update-Database
This works fine, however if I add in the line commented out above to set the default schema (both projects use the same schema), Update-Database fails in the second project with the error "There is already an object named '__MigrationHistory' in the database.".
By running "Update-Database -Verbose" I can see that with the default schema changed, "CREATE TABLE [blogtest].[__MigrationHistory]" is executed for the second project; if I don't change the default schema it only tries to create this table the first time.
Is this a bug in Entity Framework, or am I missing something?
Turns out that this is reported in Codeplex as a bug in EF6.
https://entityframework.codeplex.com/workitem/1685
The workaround shown there is to use a custom HistoryContext to set the default schema:
internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication11.MyContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetHistoryContextFactory("System.Data.SqlClient", (c, s) => new MyHistoryContext(c, s));
}
}
internal class MyHistoryContext : HistoryContext
{
public MyHistoryContext(DbConnection existingConnection, string defaultSchema) : base(existingConnection, defaultSchema)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("foo");
}
}
I am struggling with using multiple dbContext with an single web application in ASP.NET MVC 5. I am following code First existing database design approach.
so i have created dashboardModel using ADO.NET Entity model, that comes with its own dbContext (DashboardContext) and then roleModel using again ADO.net Entity Model (dbContext = RoleContext).
I want to keep similar concern of model separtate and their individual DBContext.
On creating DashboardModel, code run without problem but when i have created RoleModel and run; it gives me error on Dashboard controller ==> MetadataException was unhandled by user code
public DashboardContext()
: base("name=DashboardContext")
{
}
////
public class DashboardController : Controller
{
//
// GET: /Dashboard/
public ActionResult Home()
{
using (var db = new DashboardContext())
{
var query = from b in db.sys_Functions
orderby b.Function_ID
select b;
foreach(var item in query)
{
var a1 = item.Title;
}
}
return View();
}
}
//
public RoleContext()
: base("name=RoleContext")
{
}
//
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Index()
{
using(var db = new RoleContext())
{
var query = from x in db.AspNetRoles
orderby x.Name
select x;
foreach(var item in query)
{
var t = item.Name;
}
}
return View();
}
}
Many Thanks
I want to keep similar concern of model separtate and their individual DBContext.
DbContext is the abstraction for a database. So unless you are connecting your entities to different databases, there's no reason to use different Db contexts.
Note: this may not be so related to the question
I wanted to make two ApplicationDbContext with two different connections in ASP.NET MVC 5 (not ASP.NET CORE)
This is what worked for me, first you will need to add a second / overloaded constructor to ApplicationDbContext
Then add another ApplicationDbContext class like "ReadOnly_1_Local_ApplicationDbContext" that inherits the orignial ApplicationDbContext not the "IdentityDbContext" and make its constructor calls the overloaded base constructor with your new connection
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("<your connection>", throwIfV1Schema: false)
{
}
public ApplicationDbContext(string nameOrConnectionString) : base(nameOrConnectionString, throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
public class ReadOnly_1_Local_ApplicationDbContext : ApplicationDbContext
{
public ReadOnly_1_Local_ApplicationDbContext() : base("<your read only connection>")
{
}
}
Usage (I stopped sync from the first db to the read only one and changed the data in one of them to see it really connects to the other db)
public ActionResult TestMultiDbContext_1()
{
var db_context = new ApplicationDbContext();
return Content(db_context.Shipments.Find(123456).CustomerName); // name #1
}
public ActionResult TestMultiDbContext_2()
{
var db_context = new ReadOnly_1_Local_ApplicationDbContext();
return Content(db_context.Shipments.Find(123456).CustomerName); //name #2
}
That is tested with code first migrations and does not cause any issue and is not generating any extra migrations.
If you are adding another connection for entirely new db (not duplicated one), just make another class that inherits the IdentityDbContext normally
Thanks