Questions tagged «entity-framework-core»

实体框架(EF)核心是Microsoft开发的一种开源多平台ORM。如果适用,请添加特定于版本的标签。不要将此标签用于实体框架问题。请改用实体框架。


7
如何在单元测试之间重置EF7 InMemory提供程序?
我正在尝试使用EF7 InMemory提供程序进行单元测试,但是两次测试之间InMemory数据库的持久性导致我遇到问题。 以下代码演示了我的问题。一个测试将起作用,而另一个测试将始终失败。即使我在两次测试之间将_context设置为null,第二次测试运行仍将始终包含4条记录。 [TestClass] public class UnitTest1 { private SchoolContext _context; [TestInitialize] public void Setup() { Random rng = new Random(); var optionsBuilder = new DbContextOptionsBuilder<SchoolContext>(); optionsBuilder.UseInMemoryDatabase(); _context = new SchoolContext(optionsBuilder.Options); _context.Students.AddRange( new Student { Id = rng.Next(1,10000), Name = "Able" }, new Student { Id = rng.Next(1,10000), Name = …

5
如何使用Entity Framework Core模拟异步存储库
我正在尝试为调用异步存储库的类创建一个单元测试。我正在使用ASP.NET Core和Entity Framework Core。我的通用存储库如下所示。 public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class { private readonly SaasDispatcherDbContext _dbContext; private readonly DbSet<TEntity> _dbSet; public EntityRepository(SaasDispatcherDbContext dbContext) { _dbContext = dbContext; _dbSet = dbContext.Set<TEntity>(); } public virtual IQueryable<TEntity> GetAll() { return _dbSet; } public virtual async Task<TEntity> FindByIdAsync(int id) { return await …

12
EntityTypeBuilder在EF Core中不包含ToTable的定义
我有以下示例代码: using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Models; namespace MySampleNamespace { public class MyDbContext : DbContext { public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } public DbSet<User> Users { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { new UserMap(modelBuilder.Entity<User>()); } public class UserMap { public UserMap(EntityTypeBuilder<User> entityBuilder) { entityBuilder.ToTable("User"); entityBuilder.Property(s => …

1
ASP.NET添加迁移“复合主键错误”如何使用流畅的API
您好,我正在创建Web应用程序,并且已经安装了Microsoft.entityFrameworkCore和Microsoft.entityFrameworkCore.Tools。 在程序包管理器控制台中执行添加迁移的过程中,出现错误 “ System.InvalidOperationException:实体类型'Attends'具有使用数据注释定义的复合主键。要设置复合主键,请使用fluent API “ 这是我在实体文件夹中的代码。 using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace _3241_farmDb.Entities { public class Farm { [Required, MaxLength(30)] [Key] public string FarmName { get; set; } [Required, MaxLength(15)] public string FarmCity { get; set; } [Required, MaxLength(9)] public string FarmerSSN …

9
如何使用EF Core将JSON存储在实体字段中?
我正在使用.NET Core(针对.NETStandard 1.4)创建可重用的库,并且正在使用Entity Framework Core(这两个都是新的)。我有一个看起来像这样的实体类: public class Campaign { [Key] public Guid Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } public JObject ExtendedData { get; set; } } 并且我有一个定义DbSet的DbContext类: public DbSet<Campaign> Campaigns { get; set; } (我还在DI上使用Repository模式,但我认为这不相关。) 我的单元测试给我这个错误: System.InvalidOperationException:无法确定类型为“ JContainer”的导航属性“ JToken.Parent”表示的关系。手动配置关系,或从模型中忽略此属性。 有没有办法表明这不是关系但是应该存储为大字符串?

11
错误:实体类型需要主键
我想扩大这个线程问的问题 将列表框绑定到observablecollection 通过赋予它持久化数据的能力。除了我安装了Entity Framework Core,创建了一个DbContext用于保存记录的类之外,该结构基本相同。我添加了一个按钮来将数据集保存到SQL Server。我没有遇到编译错误,但是当我尝试将数据保存到数据库中时,出现了此运行时异常: Message =实体类型“ Fruit”要求定义主键。 下面列出了整个异常的整体 未处理System.InvalidOperationException HResult = -2146233079 消息=实体类型“水果”要求定义主键。 源= Microsoft.EntityFrameworkCore 堆栈跟踪: 在Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(字符串消息) 在Microsoft.EntityFrameworkCore.Internal.ModelValidator.EnsureNonNullPrimaryKeys(IModel模型) 在Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel模型) 在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel上的Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel模型) (DbContext上下文,IConventionSetBuilder ConventionSetBuilder,IModelValidator验证器) 在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。<> c__DisplayClass14_0.b__0(对象k) 在System.Collections.Concurrent.ConcurrentDictionary 2.GetOrAdd(TKey key, Func2 valueFactory) 在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(的DbContext上下文,IConventionSetBuilder conventionSetBuilder,IModelValidator验证器) 在Microsoft.EntityFrameworkCore.Internal.LazyRef 2上的Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()2.Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSiteProvider ) 上的VisitCallSite(IServiceCallSite callSite,TArgument参数 )1.get_Value() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_6(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactoryService(FactoryService factoryService, ServiceProvider provider) at …

4
检测到不支持的.Net Core 3.0可能的对象周期
我有2个实体与一对多相关 public class Restaurant { public int RestaurantId {get;set;} public string Name {get;set;} public List<Reservation> Reservations {get;set;} ... } public class Reservation{ public int ReservationId {get;set;} public int RestaurantId {get;set;} public Restaurant Restaurant {get;set;} } 如果我尝试使用我的API预订餐厅 var restaurants = await _dbContext.Restaurants .AsNoTracking() .AsQueryable() .Include(m => m.Reservations).ToListAsync(); ..... 我收到错误消息,因为对象包含彼此的引用。有相关的文章建议创建单独的模型 或添加NewtonsoftJson配置 问题是我不想创建单独的模型,第二个建议没有帮助。有没有没有循环关系的加载数据的方法吗?* …

2
如何在实体框架核心模型中使用C#8.0可空引用类型?
我在.NET Core 3.0项目上启用C#8.0可空引用类型。该项目使用Entity Framework Core 3.0访问数据库。 以下是标题不应为null的数据模型。 public class Vehicle { public int Id { get; private set; } public string Title { get; private set; } // Entity Framework Core is instructed to bind to the private _drivers field in a configuration builder private readonly List<Driver> _drivers = new …

3
实体框架核心中的强类型ID
我正在尝试创建一个强类型的Id类,该类现在在内部保持“ long”。实施如下。我在实体中使用此控件时遇到的问题是,实体框架向我发送一条消息,指出属性ID已映射到其上。请参阅IEntityTypeConfiguration下面的内容。 注意:我的目标不是严格的DDD实现。因此,在评论或回答时请记住这一点。键入后的整个id Id是供开发人员进入的项目,他们被强烈键入要在其所有实体中使用Id,当然可以转换为long(或BIGINT)-但对于其他人则很清楚。 在类和配置下面,这不起作用。可以在https://github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31中找到该存储库, Id上的课程(现在已注释掉):https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/blob/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign/Id.cs Entity和ValueObject类(Entity属性Id的类型为Id.cs(在上面):https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Common/Kf.CANetCore31/DomainDrivenDesign 可在以下位置进行配置:https : //github.com/KodeFoxx/Kf.CleanArchitectureTemplate.NetCore31/tree/master/Source/Infrastructure/Persistence/Kf.CANetCore31.Infrastructure.Persistence.Ef/EntityTypeConfigurations Id类实现(现在标记为过时,因为在找到解决方案之前我放弃了这个想法) namespace Kf.CANetCore31.DomainDrivenDesign { [DebuggerDisplay("{DebuggerDisplayString,nq}")] [Obsolete] public sealed class Id : ValueObject { public static implicit operator Id(long value) => new Id(value); public static implicit operator long(Id value) => value.Value; public static implicit operator Id(ulong value) …

3
在EF Core中指定Azure SQL Server版本而不中断本地开发
实体框架核心引入了HasServiceTier和HasPerformanceLevel方法来更改Azure SQL服务器的版本。您可以像这样在OnModelCreating中使用它们: protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasServiceTier("Basic"); modelBuilder.HasPerformanceLevel("Basic"); } 如果您使用Add-Migration Add-Migration,您将获得如下迁移: public partial class ChangedDatabaseServiceTierToBasic : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterDatabase() .Annotation("SqlServer:EditionOptions", "EDITION = 'Basic', SERVICE_OBJECTIVE = 'Basic'"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterDatabase() .OldAnnotation("SqlServer:EditionOptions", "EDITION = 'Basic', SERVICE_OBJECTIVE = 'Basic'"); …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.