I have a .NET Core API using Entity Framework Core. We use .FromSQL()
to execute stored procedures. The problem I'm having is we have two queries that return Account
information - one for a single account and one for a paged list of accounts.
The account list returns a column for RowCount
which the single account query does not return, so now the single account query returns an error (Rowcount
returns the total number of accounts in the database, not just the accounts on the requested page so you know how many pages of data there are).
The error:
The required column 'RowCount' was not present in the results of a 'FromSql' operation
Here is the model
public class Account
{
[Key]
public long AccountId { get; set; }
public string AccountName { get; set; }
public bool IsDeleted { get; set; }
public int RowCount { get; set; }
[NotMapped]
public bool Found => AccountId > 0;
}
And our dbContext
public class AccountDbContext : DbContext
{
private DbSet<Account> TAccount { get; set; }
public AccountDbContext(DbContextOptions<AccountDbContext> options) : base(options)
{
}
public Account GetAccountById(long accountId)
{
var pAccount = new SqlParameter("accountId", accountId);
Account account = TAccount.FromSql("EXEC dbo.SPR_Account_GetById @accountId", pAccount).FirstOrDefault();
return account;
}
public List<Account> GetAccounts(int offset, int limit)
{
var pOffset = new SqlParameter("offset", offset);
var pLimit = new SqlParameter("limit", limit);
var dataSet = TAccount.FromSql($"EXEC dbo.SPR_Account_GetAll @offset=@offset,@limit=@limit", pOffset, pLimit).ToList();
return dataSet;
}
}
My question: is there a way to reuse this model for both queries? I think it's dumb to create a second model with identical properties. And I can never get entity to play nice with inheritance. It always gives me an error about Discrimitator
not being found.
[NotMapped]
for additional fields. Any ideas about my Discriminator error if I move rowcount to a subclass? ` public class AccountCount : Account { public int RowCount { get; set; } }`[NotMapped]
would actually prevent it from even binding. But that means your row count would also not bind on your GetAll stored procedure, so that's no option. If you are able to influence or change the design of the database, then Entity Framework Core has more flexible support for views. Your view could return the needed row count and then your entity would be happy. Your inheritance option would throw you more difficulty in your path then just returning a row count of 1.