Open Closed

Creating Entity without inheriting Entity base class. #929


User avatar
0
suraj.kumbhar created

@maliming In ABP.IO we are creating an entities like this which supports repository pattern.

public class Book : Entity<long> { public string Name { get; set; }

public float Price { get; set; }

}

private readonly IRepository<Book,long> _bookRepository;

but i want to create a class which will not inherit Entity.

public class Book { public long Id {get;set;}

public string Name { get; set; }

public float Price { get; set; }

}

private readonly IRepository<Book,long> _bookRepository it gives erros at this line if we didnt pass Entity.

can i use this class with Repository pattern and if not then what approach should i take.

waiting for your urgent response.


2 Answer(s)
  • User Avatar
    0
    Moyaoxiang created

    Hi suraj.kumbhar, Due to the generic constraints of IRepository, the entity class must inherit from the IEntity/IEntity<TKey> interface. If you need to create an entity class that does not inherit from IEntity, you can only access entity data through DbContext. e.g.

    public class CustomRepository : ICustomRepository
    {
        private readonly IDbContextProvider<IoTProjectDbContext> _dbContextProvider;
    
        protected virtual Task<IoTProjectDbContext> GetDbContextAsync()
        {
            return _dbContextProvider.GetDbContextAsync();
        }
    
        public CustomRepository(IDbContextProvider<IoTProjectDbContext> dbContextProvider)
        {
            _dbContextProvider = dbContextProvider;
        }
    
        public async Task<DeviceTests> GetAsync(long id)
        {
            var provider = await GetDbContextAsync();
            return await provider.DeviceTests.FirstOrDefaultAsync(e => e.Id == id);
        }
    }
    
  • User Avatar
    0
    ServiceBot created
    Support Team Automatic process manager

    This question has been automatically marked as stale because it has not had recent activity.

Boost Your Development
ABP Live Training
Packages
See Trainings
Mastering ABP Framework Book
Do you need assistance from an ABP expert?
Schedule a Meeting
Mastering ABP Framework Book
The Official Guide
Mastering
ABP Framework
Learn More
Mastering ABP Framework Book
Made with ❤️ on ABP v9.2.0-preview. Updated on March 17, 2025, 10:38