简体   繁体   中英

How to initialize DbContext from child project?

I have two web project, first is framework and other is shopping , both of projects are WebForm and i'm using Entity Framework. i want to implement GenericRepository in framework project and then use it in shopping project. framework project has it's own DbContext named FrameworkContext and shopping project has it's own DbContext thats extends FrameworkContext and named AppContext .

public class FrameworkContext : DbContext
{
    public FrameworkContext() : base("name=AppContext")
    {
    }
}

public class AppContext : FrameworkContext
{
    public AppContext()
    {
    }

    public DbSet<Car> cars { get; set; }
    public DbSet<Plaque> plaques { get; set; }
}


public class GenericRepository<T, Key> : IGenericRepository<T, Key> where T : BaseEntity
{
    private FrameworkContext _dbContext;

    public GenericRepository()
    {
    }

    public FrameworkContext context
    {
        get { return _dbContext; }
        set { _dbContext = value; }
    }

    public IEnumerable<T> getAll()
    {
        return _dbContext.Set<T>().ToList();
    }
}

web.config of shopping project

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="AppContext" providerName="System.Data.SqlClient" connectionString="Server=ASUS-PC\SQLEXPRESS;Database=testFramework;Integrated Security=True;" />
  </connectionStrings>
</configuration>

now, i add framework project as a reference to shopping project. when i call getAll() method of Repository this below exception is thrown:

在此处输入图片说明

UPDATE

i'm used from @octavioccl's solution to solve my problems. now another exception occurred: 在此处输入图片说明

and these are my BaseEntity class and Car class:

namespace framework.Model
{
    public abstract class BaseEntity
    {
        [Key]
        public Int64 id { get; set; }

        public string createdDate { get; set; }
    }
}


namespace shopping.model
{
    public class Car : BaseEntity
    {
        public string name { get; set; }
        public int year { get; set; }

        public virtual List<Plaque> plaques { get; set; }
    }
}

I don't see that you initialize your dbContext variable on your GenericRepository class, try initializing this variable in the constructor:

 public GenericRepository()
{
 _dbContext=new FrameworkContext();
}

Update

Well there are many ways to solve your second exception, the problem is because your context doesn't know about your entity:

A solution could be declaring a property on your context as follow:

public DbSet<Car> Cars{get;set;}

Or using Fluent Api, for example, overriding OnModelCreating method and doing something like this:

 modelBuilder.Entity<Car>().HasKey(c=>c.Id);

But the best way is create a mapping class for each entity:

public class CarMap : EntityTypeConfiguration<Car>
{
    public CarMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);
    }
}

An later you only need to do this in your OnModelCreating method to discover all the mappings:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
        modelBuilder.Configurations.AddFromAssembly(typeof(FrameworkContext).Assembly);// set here the asembly where there are all your mapping classes.
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM