实体框架核心问题:获取记录时出错:无法转换类型的对象

问题描述 投票:0回答:1

我有一个问题,当我在一个范围内的一个类中调用多个存储库类型时,我收到一个错误:

System.InvalidCastException HResult=0x80004002 Message=无法将“PortfolioManager.Base.Entities.RecordEntity”类型的对象转换为“PortfolioManager.Base.Entities.CommodityEntity”类型。来源 = Microsoft.EntityFrameworkCore.Relational StackTrace:在 Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.AsyncEnumerator.d__20.MoveNext() 在 System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable1.ConfiguredValueTaskAwaiter.GetResult() 在 Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.d__67` 1.MoveNext()

我还没有找到解决办法。存储库继承自基础存储库并实现接口。项目:https://github.com/TomasSobotaT/Portfolio_Manager_V2

public class BaseRepository<T>(ApplicationDbContext applicationDbContext, IUserContext userContext) : IBaseRepository<T> where T : BaseEntity 
{
    protected readonly ApplicationDbContext applicationDbContext = applicationDbContext;
    protected readonly IUserContext userContext = userContext;
    protected readonly DbSet<T> dbSet = applicationDbContext.Set<T>();

    public async Task<IEnumerable<T>> GetAllAsync()
    {
        return await dbSet.Where(r => !r.IsDeleted).ToListAsync();
    }

    public async Task<T> GetAsync(int id)
    {
        return await dbSet.Where(r => r.Id == id  
                                      && !r.IsDeleted)
                          .FirstOrDefaultAsync();
    }

    public async Task UpdateAsync(T entity)
    {
        entity.UpdatedBy = userContext?.User?.Identity?.Name;
        entity.UpdatedDate = DateTime.Now;

        dbSet.Update(entity);

        await SaveChangesToDatabaseAsync();
    }

    public async Task AddAsync(T entity)
    {
        entity.UpdatedBy = userContext?.User?.Identity?.Name;
        entity.CreatedBy = userContext?.User?.Identity?.Name;

        entity.CreatedDate = DateTime.Now;
        entity.UpdatedDate = DateTime.Now;

        await dbSet.AddAsync(entity);
        await SaveChangesToDatabaseAsync();
    }

    public async Task DeleteAsync(int id)
    {
        var entity = await GetAsync(id);

        if (entity is not null)
        {
            entity.UpdatedBy = userContext?.User?.Identity?.Name;
            entity.UpdatedDate = DateTime.Now;
            entity.IsDeleted = true;
            await UpdateAsync(entity);
        }

        await SaveChangesToDatabaseAsync();
    }

    private async Task SaveChangesToDatabaseAsync()
    {
        await this.applicationDbContext.SaveChangesAsync();
    }
}

public class CommodityRepository(ApplicationDbContext applicationDbContext, IUserContext userContext)
    : BaseRepository<CommodityEntity>(applicationDbContext, userContext), ICommodityRepository
{
}

public interface ICommodityRepository : IBaseRepository<CommodityEntity>
{
}

enter image description here

 modelBuilder.Entity<BaseEntity>().UseTpcMappingStrategy();

 modelBuilder.Entity<RecordEntity>(entity =>
 {
     entity.HasBaseType<BaseEntity>();

     entity.HasOne(r => r.User)
         .WithMany(u => u.Records)
         .HasForeignKey(r => r.UserId)
         .OnDelete(DeleteBehavior.Restrict);

     entity.HasOne(r => r.Commodity)
         .WithMany(c => c.Records)
         .HasForeignKey(r => r.CommodityId)
         .OnDelete(DeleteBehavior.Restrict);

     entity.Property(p => p.Amount).HasColumnType("decimal(18,2)");
 });

 modelBuilder.Entity<CommodityEntity>(entity =>
 {
     entity.HasBaseType<BaseEntity>();

     entity.HasOne(c => c.Price)
         .WithMany(p => p.Commodity)
         .HasForeignKey(c => c.PriceId)
         .OnDelete(DeleteBehavior.Restrict);
 });

 modelBuilder.Entity<PriceEntity>(entity =>
 {
     entity.HasBaseType<BaseEntity>();

     entity.Property(p => p.PriceCzk).HasColumnType("decimal(18,2)");
     entity.Property(p => p.PriceUsd).HasColumnType("decimal(18,2)");
 });

public class RecordEntity : BaseEntity
{
    public UserEntity User { get; set; }

    public int UserId {  get; set; }

    public decimal Amount { get; set; }

    public int CommodityId { get; set; }

    public CommodityEntity Commodity { get; set; }
}

public class UserEntity : IdentityUser<int>
{
    public ICollection<RecordEntity> Records { get; set; }

    public bool IsDeleted { get; set; }
}

public class CommodityEntity : BaseEntity
{
    public string Name { get; set; }

    public CommodityTypes CommodityType {  get; set; }

    public ICollection<RecordEntity> Records { get; set; }

    public int PriceId { get; set; }

    public PriceEntity Price { get; set; }
}
c# asp.net database entity-framework-core repository
1个回答
0
投票

没有提供足够的信息来完全解决问题。不过,您可以在 RecordEntity 类中使用类似的东西。

public static implicit operator RecordEntity(ComodityEntity comodityEntity) { return new RecordEntity { // For example Id = comodityEntity.Id, Name = comodityEntity.Name, ParentId = comodityEntity.ParentId }; }

如果这不能解决您的问题,您应该在控制器或使用 RecordEntity 存储库的服务上使用调试器。

© www.soinside.com 2019 - 2024. All rights reserved.