关于此状态的大多数答案表明,上下文上的DbSet必须是属性。但是,在这种情况下似乎并非如此,因为此上下文的DbSet是一个属性。这是我可以用来重现问题的示例代码。请告知。
DbContext
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Dal
{
public class SampleContext : DbContext
{
public DbSet<Model.ItemCode> ItemCodes { get; set; }
public SampleContext(DbContextOptions<SampleContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new Mapping.ItemCodeConfiguration());
base.OnModelCreating(modelBuilder);
}
public async Task<IEnumerable<Model.ItemCode>> GetCodesByGroup(int group)
{
return await ItemCodes.Where(g => g.GroupId == group).ToListAsync();
}
}
}
型号
namespace Dal.Model
{
public class ItemCode
{
public int Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public int KcId { get; set; }
public int CategoryId { get; set; }
public int GroupId { get; set; }
}
}
数据映射
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Dal.Mapping
{
public class ItemCodeConfiguration : IEntityTypeConfiguration<Model.ItemCode>
{
public void Configure(EntityTypeBuilder<Model.ItemCode> builder)
{
builder.HasKey(b => b.Id);
builder.Property(b => b.Description)
.HasColumnName("Description")
.HasColumnType("nvarchar(255)")
.IsRequired();
builder.Property(b => b.Code)
.HasColumnName("Code")
.IsRequired();
builder.Property(b => b.KcId)
.HasColumnName("KcId");
builder.Property(b => b.Quantity)
.HasColumnName("Quantity");
builder.Property(b => b.GroupId)
.HasColumnName("GroupId")
.IsRequired();
builder.Property(b => b.CategoryId)
.HasColumnName("CategoryId")
.IsRequired();
builder.ToTable("ItemCode", "lookup");
}
}
}
测试类
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace Dal.Test
{
public class DataTest
{
readonly SampleContext context;
public DataTest()
{
var testContextOptions = new DbContextOptionsBuilder<SampleContext>();
testContextOptions.UseSqlServer(@"Server=localServerName;Database=SampleAppDb;User Id=SampleUser;Password=sampleUser!Password");
testContextOptions.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
context = new SampleContext(testContextOptions.Options);
}
[Fact]
public async void Test1()
{
var codes = await context.GetCodesByGroup(1);
Assert.NotNull(codes);
Assert.NotEmpty(codes);
}
}
}
答案 0 :(得分:1)
找到答案,这是一个愚蠢的错误。错误是存在可空的int列,但属性不可为空。 更正的课程:
namespace Dal.Model
{
public class ItemCode
{
public int Id { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public int? Quantity { get; set; }
public int? KcId { get; set; }
public int CategoryId { get; set; }
public int GroupId { get; set; }
}
}