简体   繁体   English

实体框架核心与实体框架之间的冲突

[英]Conflict between Entity Framework Core and Entity Framework

I have already created mssql db and project (class library) for data access layer at .net framework. 我已经为.net框架中的数据访问层创建了mssql db和项目(类库)。 Then I created project at asp.net core. 然后,我在asp.net核心创建了项目。 To access to this db I use in startup class within ConfigureServices method. 要访问此数据库,我在ConfigureServices方法中的启动类中使用。 I use EF core in asp.net core project. 我在asp.net核心项目中使用EF核心。

services.AddDbContext<TradeEvoDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("SqlDb")));
 services.AddIdentity<ApplicationUser, IdentityRole>()
         .AddEntityFrameworkStores<TradeEvoDbContext>()
         .AddDefaultTokenProviders();

And here is my DbContext class which reference to my class library proj. 这是我的DbContext类,它引用了我的类库proj。

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeEvo.Chat.Identity;
using TradeEvo.DAL.Models;

namespace TradeEvo.Chat.Models
{
    public class TradeEvoDbContext : IdentityDbContext<ApplicationUser>
    {
        public DbSet<GlobalSettings> GlobalSettings { get; set; }
        public DbSet<UserApiSettings> ApiSettings { get; set; }
        public DbSet<UserEBaySettings> EBaySettings { get; set; }
        public DbSet<User1CSettings> User1CSettings { get; set; }
        public DbSet<UserPayPalSettings> PayPalSettings { get; set; }
        public DbSet<CompanyInfo> CompanyInfo { get; set; }
        public DbSet<PromInfo> PromInfo { get; set; }
        public DbSet<ProductInfoMultiLang> ProductInfoMultiLang { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<PosterImage> PosterImages { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<OrderNote> OrderNotes { get; set; }
        public DbSet<OrderItem> OrderItems { get; set; }
        public DbSet<OrderItemMont> OrderItemsMont { get; set; }
        public DbSet<OrderItemMontKey> OrderItemsMontKey { get; set; }
        public DbSet<OrderItemMontLink> OrderItemsMontLink { get; set; }
        public DbSet<OrderItemMontFile> OrderItemsMontFile { get; set; }
        public DbSet<UserInfo> UserInfo { get; set; }
        public DbSet<BlogPost> BlogPosts { get; set; }
        public DbSet<BlogComment> BlogComments { get; set; }
        public DbSet<TradeEvo.DAL.Models.Chat> Chats { get; set; }
        public DbSet<Message> Messages { get; set; }
        public DbSet<Status> Status { get; set; }
        public DbSet<StatusType> StatusType { get; set; }
        public DbSet<StatusTypeMapping> StatusTypeMapping { get; set; }
        public DbSet<DistributorProduct> DistributorProducts { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<ProductType> ProductType { get; set; }
        public DbSet<ProductContent> ProductContent { get; set; }
        public DbSet<ProductInfo> ProductInfo { get; set; }
        public DbSet<ProductMontChanges> ProductMontChanges { get; set; }
        public DbSet<ProductGenreMapping> ProductGenreMapping { get; set; }
        public DbSet<ProductAttribute> ProductAttributes { get; set; }
        public DbSet<ProductAttributeValue> ProductAttributeValues { get; set; }
        public DbSet<ProductAttributeMapping> ProductAttributeMapping { get; set; }
        public DbSet<ProductAttributeCombination> ProductAttributeCombinations { get; set; }
        public DbSet<ProductAttributeCombinationMapping> ProductAttributeCombinationMapping { get; set; }
        public DbSet<ProductCharacteristic> ProductCharacteristics { get; set; }
        public DbSet<ProductCharacteristicValue> ProductCharacteristicValues { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<ProductListAttribute> ProductListAttributes { get; set; }
        public DbSet<ProductPromAttribut> ProductPromAttributes { get; set; }
        public DbSet<ProductList> ProductLists { get; set; }
        public DbSet<ProductListMapping> ProductListMapping { get; set; }
        public DbSet<ProductAvailability> ProductAvailability { get; set; }
        public DbSet<Currency> Currencies { get; set; }
        public DbSet<Language> Languages { get; set; }
        public DbSet<UserLanguage> UserLanguages { get; set; }
        public DbSet<ResourceMultiLang> ResourceMultiLang { get; set; }
        public DbSet<PromUaCategories> PromUaCategories { get; set; }
        public DbSet<OrderPromInfo> OrderPromInfo { get; set; }
        public DbSet<OrderItemProm> OrderItemProm { get; set; }
        public DbSet<Country> Countries { get; set; }
        public DbSet<Bank> Bank { get; set; }
        public DbSet<RecipientAddress> RecipientAddress { get; set; }
        public DbSet<SenderAddress> SenderAddress { get; set; }
        public DbSet<OrderInvoice> OrderInvoices { get; set; }
        public DbSet<CityNP> CityNP { get; set; }
        public DbSet<StreetNP> StreetNP { get; set; }
        public DbSet<WarehouseNP> WarehouseNP { get; set; }
        public DbSet<Setting> Settings { get; set; }
        public DbSet<OrderManufacturer> OrderManufacturs { get; set; }
        public DbSet<Purse> Purses { get; set; }
        public DbSet<PaymentSystem> PaymentSystem { get; set; }
        public DbSet<MoneyMovement> MoneyMovement { get; set; }
        public DbSet<MoneyMovementData> MoneyMovementData { get; set; }
        public DbSet<MoneyMovementType> MoneyMovementType { get; set; }
        public DbSet<ProductMultiDownloadData> ProductMultiDownloadData { get; set; }
        public DbSet<Address> Address { get; set; }
        public DbSet<Warehouse> Warehouses { get; set; }
        public DbSet<ShippingService> ShippingServices { get; set; }
        public DbSet<ShippingServiceUserMapping> ShippingServiceUserMapping { get; set; }
        public DbSet<ShippingServiceCountryMapping> ShippingServiceCountryMapping { get; set; }
        public DbSet<ShippingServiceProductMapping> ShippingServiceProductMapping { get; set; }
        public DbSet<UPAddress> UPAddress { get; set; }
        public DbSet<UPaddresses> UPaddresses { get; set; }
        public DbSet<UPEmails> UPEmails { get; set; }
        public DbSet<UPPhones> UPPhones { get; set; }
        public DbSet<UPClient> UPClient { get; set; }
        public DbSet<NPClient> NPClient { get; set; }
        public DbSet<PAdresses> PAdresses { get; set; }
        public DbSet<RecipientAddressCustomService> RecipientAddressCustomService { get; set; }
        public DbSet<UPShipment> UPShipment { get; set; }
        public DbSet<UPParcels> UPParcels { get; set; }
        public DbSet<UPParcelItems> UPParcelItems { get; set; }
        public DbSet<UPDiscount> UPDiscount { get; set; }
        public DbSet<UPDiscountPerClient> UPDiscountPerClient { get; set; }
        public DbSet<UPInternationalData> UPInternationalData { get; set; }
        public DbSet<UPLifeCycle> UPLifeCycle { get; set; }
        public DbSet<ImportExportSettings> ImportExportSettings { get; set; }
        public DbSet<ImportExportStructure> ImportExportStructures { get; set; }
        public TradeEvoDbContext(DbContextOptions<TradeEvoDbContext> options)
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

So, when i try to access my users table such as: 因此,当我尝试访问我的用户表时,例如:

var user = _context.Users.Where(x => x.Id == args[1]).FirstOrDefault();

Or: 要么:

var user = await _userManager.Users.FindByIdAsync(args[1]);

I got next exception: 我得到下一个例外:

{System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. File can not be found.
File name: 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

All stacktrace is: 所有堆栈跟踪为:

{System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Не удается найти указанный файл.
File name: 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
   at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
   at System.Reflection.RuntimeMethodInfo.GetParametersNoCopy()
   at System.Reflection.RuntimePropertyInfo.GetIndexParametersNoCopy()
   at System.Reflection.RuntimePropertyInfo.GetIndexParameters()
   at System.Attribute.GetIndexParameterTypes(PropertyInfo element)
   at System.Attribute.InternalGetCustomAttributes(PropertyInfo element, Type type, Boolean inherit)
   at System.Reflection.CustomAttributeExtensions.GetCustomAttributes[T](MemberInfo element, Boolean inherit)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.NotMappedMemberAttributeConvention.Apply(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnEntityTypeAdded(InternalEntityTypeBuilder entityTypeBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(EntityType entityType)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.AddEntityType(Type type, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(TypeIdentity type, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalModelBuilder.Entity(Type type, ConfigurationSource configurationSource)
   at Microsoft.EntityFrameworkCore.ModelBuilder.Entity(Type type)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelCustomizer.FindSets(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelCustomizer.Customize(ModelBuilder modelBuilder, DbContext context)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__0(Object k)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_Model()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at TradeEvo.Chat.Controllers.HomeController.<ChatAsync>d__15.MoveNext() in myproj

And my controller looks like: 我的控制器看起来像:

        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly ILogger _logger;
        private readonly TradeEvoDbContext _context;
        public HomeController(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            ILogger<HomeController> logger,
            TradeEvoDbContext context)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _context = context;
        }

If I use nuget manager and install Microsoft.AspNet.Identity.EntityFramework, I will fix only this error and got new also at this line of code. 如果我使用nuget Manager并安装Microsoft.AspNet.Identity.EntityFramework,我将仅修复此错误,并在此代码行中重新安装。 System.Web.HttpPostedFile ... File can not be found

What am I doing wrong? 我究竟做错了什么? Or how to connect to existing db ? 或者如何连接到现有的数据库? I'm stuck. 我被卡住了。

Edit #1 Asp.net Core project, csproj file: 编辑#1 Asp.net Core项目,csproj文件:

<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="2.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.Owin" Version="2.0.2" />
    <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.0.0-preview2-final" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.1" />

Edit #2 What's wrong? 编辑#2怎么了? 在此处输入图片说明

Please check in your project references what is the version of 'Microsoft.AspNet.Identity.EntityFramework' library and cross verify it with the version in web.config file for the same library. 请在项目引用中检查“ Microsoft.AspNet.Identity.EntityFramework”库的版本,并与同一库的web.config文件中的版本进行交叉验证。 Change the version in web.config file to the correct version of the library referenced in the project. 将web.config文件中的版本更改为项目中引用的库的正确版本。 This will resolve your issue. 这样可以解决您的问题。

You can also check the version in packages.config file, 您也可以在packages.config文件中检查版本,

packages.config

And update the version in web.config as below, 并如下更新web.config中的版本,

web.config

Library references implicitly include libraries referenced by that library. 库引用隐式包括该库引用的库。 Put more simply, if you have library X that references EF 6 and you include it library Y that references EF Core. 简而言之,如果您拥有引用EF 6的库X,并且包含了引用EF Core的库Y。 Library Y will then have references to both EF 6 and EF core. 然后,库Y将同时引用EF 6和EF内核。

You can mix and match your usage of EF6/EF Core, but you must segregate them from each other. 您可以混合使用EF6 / EF Core,但是必须将它们彼此隔离。 If you need some portion of the library that references EF 6, you'll have to break that out into it's own separate library with no references to EF 6. 如果您需要在库中引用EF 6的某些部分,则必须将其分解为它自己的独立库,而无需引用EF 6。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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