Incorrect number of arguments for PROCEDURE ntc_sales.AgentAmounts; expected 1, got 0 - entity-framework

Here i am tring to call the stored procedure with paramter using entityframework
it's get the error:Incorrect number of arguments for PROCEDURE ntc_sales.AgentAmounts; expected 1, got 0
Below code
`enter code here`[HttpGet]
public virtual List<AgentAmounts> AgentAmountbyId(int id)
{
string SQLQuery = #"call AgentAmounts();";
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
//List<object> listobj = new List<object>();
List<AgentAmounts> data = objectContext.ExecuteStoreQuery<AgentAmounts>(SQLQuery,
id).AsQueryable().ToList();
return data;
}

public virtual List<AgentAmounts> AgentAmountbyId(int id)
{
string SQLQuery = #"call AgentAmounts(#vagent);";
var objectContext = ((IObjectContextAdapter)db).ObjectContext;
//List<object> listobj = new List<object>();
List<AgentAmounts> data = objectContext.ExecuteStoreQuery<AgentAmounts>(SQLQuery,new Mysqlparamter("#vagent",id).AsQueryable().ToList();
return data;
}

Related

ADO.NET add SQLParameters

I am trying to execute a stored procedure with parameters using ADO.NET in .NET Core.
When I try and pass in a SqlParameter object I get the below error.
I have a using statement at the top for System.Data.SqlClient.
Is there another way or new ways of passing Sql parameters to a stored procedure?
public async Task<List<SynchStockDto>> GetStockForSync(int locationBinId, DateTime lastSyncDate)
{
await EnsureConnectionOpenAsync();
var command = GetConnection().CreateCommand();
command.CommandText = "sp_GetStockForSync #LocationBinId, #LastSyncDate";
command.CommandType = CommandType.StoredProcedure;
command.Transaction = GetActiveTransaction();
command.Parameters.Add(new SqlParameter("LocationBinId",locationBinId)); //not finding SQLParameter method
using (var dataReader = await command.ExecuteReaderAsync())
{
var result = new List<SynchStockDto>();
while (dataReader.Read())
{
var stockItem = new SynchStockDto
{
};
result.Add(stockItem);
}
return result;
}
}

entity framework core 3 dynamic order by not working

public class Branch
{
[Sortable(OrderBy = "BranchId")]
public long BranchId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public string Type { get; set; }
}
this is my Model class and I also create a custom attribute
public class SortableAttribute : Attribute
{
public string OrderBy { get; set; }
}
now i create a pagination with orderby descending but this code not working
public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> source,
GeneralPagingRequest pagingRequest, int indexFrom = 0,
CancellationToken cancellationToken = default(CancellationToken))
{
if (indexFrom > pagingRequest.PageNumber)
{
throw new ArgumentException(
$"indexFrom: {indexFrom} > pageNumber: {pagingRequest.PageNumber}, must indexFrom <= pageNumber");
}
var count = await source.CountAsync(cancellationToken).ConfigureAwait(false);
var items = source.Skip(((pagingRequest.PageNumber - 1) - indexFrom) * pagingRequest.PageSize)
.Take(pagingRequest.PageSize);
var props = typeof(T).GetProperties();
PropertyInfo orderByProperty;
orderByProperty =
props.FirstOrDefault(x=>x.GetCustomAttributes(typeof(SortableAttribute), true).Length != 0);
if (pagingRequest.OrderBy == "desc")
{
items = items.OrderBy(x => orderByProperty.GetValue(x));
}
else
{
items = items.OrderBy(x => orderByProperty.GetValue(x));
}
var result = await items.ToListAsync(cancellationToken).ConfigureAwait(false);
var pagedList = new PagedList<T>
{
PageNumber = pagingRequest.PageNumber,
PageSize = pagingRequest.PageSize,
IndexFrom = indexFrom,
TotalCount = count,
Items = result,
TotalPages = (int) Math.Ceiling(count / (double) pagingRequest.PageSize)
};
return pagedList;
}
but the result variable create exception
.OrderBy() requires a delegate that would tell it HOW to select a key, not the key value itself. So you are looking at some meta-programming here.
Naturally, you will look at building a dynamic LINQ Expression tree that will fetch a property for you:
// your code up above
PropertyInfo orderByProperty = props.FirstOrDefault(x => x.GetCustomAttributes(typeof(SortableAttribute), true).Length != 0);
var p = Expression.Parameter(typeof(T), "x"); // you define your delegate parameter here
var accessor = Expression.Property(p, orderByProperty.GetMethod); // this basically becomes your `x => x.BranchId` construct
var predicate = Expression.Lambda(accessor, p).Compile(); // here's our problem: as we don't know resulting type at compile time we can't go `Expression.Lambda<T, long>(accessor, p)` here
if (pagingRequest.OrderBy == "desc")
{
items = items.OrderByDescending(x => predicate(x)); // passing a Delegate here will not work as OrderBy requires Func<T, TKey>
}
else
{
items = items.OrderBy(x => predicate(x)); // passing a Delegate here will not work as OrderBy requires Func<T, TKey>
}
var result = await items.ToListAsync(cancellationToken).ConfigureAwait(false);
// your code down below
Problem with the above code - you don't know TKey upfront. Therefore we will have to go a level deeper and build the whole items.OrderBy(x => x.BranchId) expression dynamically. The biggest leap of faith here will be the fact the OrderBy is an extension method and it actually resides on IQueryable type. After you've got the generic method reference, you will need to build a specific delegate type when you know your property type. So your method becomes something like this:
public static class ExtToPagedListAsync
{
private static readonly MethodInfo OrderByMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "OrderBy" && method.GetParameters().Length == 2); // you need your method reference, might as well find it once
private static readonly MethodInfo OrderByDescendingMethod = typeof(Queryable).GetMethods().Single(method => method.Name == "OrderByDescending" && method.GetParameters().Length == 2); // you need your method reference, might as well find it once
public static async Task<IPagedList<T>> ToPagedListAsync<T>(this IQueryable<T> source, GeneralPagingRequest pagingRequest, int indexFrom = 0, CancellationToken cancellationToken = default(CancellationToken))
{
if (indexFrom > pagingRequest.PageNumber)
{
throw new ArgumentException(
$"indexFrom: {indexFrom} > pageNumber: {pagingRequest.PageNumber}, must indexFrom <= pageNumber");
}
var count = await source.CountAsync(cancellationToken).ConfigureAwait(false);
var items = source.Skip(((pagingRequest.PageNumber - 1) - indexFrom) * pagingRequest.PageSize)
.Take(pagingRequest.PageSize);
var props = typeof(T).GetProperties();
PropertyInfo orderByProperty = props.FirstOrDefault(x => x.GetCustomAttributes(typeof(SortableAttribute), true).Length != 0);
var p = Expression.Parameter(typeof(T), "x");
var accessor = Expression.Property(p, orderByProperty.GetMethod);
var predicate = Expression.Lambda(accessor, p); // notice, we're not yet compiling the predicate. we still want an Expression here
// grab the correct method depending on your condition
MethodInfo genericMethod = (pagingRequest.OrderBy == "desc") ? OrderByDescendingMethod.MakeGenericMethod(typeof(T), orderByProperty.PropertyType)
:OrderByMethod.MakeGenericMethod(typeof(T), orderByProperty.PropertyType);
object ret = genericMethod.Invoke(null, new object[] { items, predicate });
items = (IQueryable<T>)ret; // finally cast it back to Queryable with your known T
var result = await items.ToListAsync(cancellationToken).ConfigureAwait(false);
var pagedList = new PagedList<T>
{
PageNumber = pagingRequest.PageNumber,
PageSize = pagingRequest.PageSize,
IndexFrom = indexFrom,
TotalCount = count,
Items = result,
TotalPages = (int)Math.Ceiling(count / (double)pagingRequest.PageSize)
};
return pagedList;
}
}
I must disclose I did get some inspiration from this answer here, so do check it out for further reading.

Returning a DataTable using Entity Framework By Executing Stored Procedure

Stored Procedure returns dynamic table which can have dynamic columns. I want to retrieve the list of data to tempResult .
IList<SqlParameter> parameters = GetCashInItemsParameters("inv.uspMonthendProces");
string queryString = CreateStoredProcedureExecuteQuery("inv.uspMonthendProcess", parameters);
var tempResult = ExecuteStoredProcedureForDataRetrieve<dynamic>(queryString, parameters.ToArray()).ToList();
CreateStoredProcedureExecuteQuery
public static string CreateStoredProcedureExecuteQuery(string storedProcedureName, IList<SqlParameter> parameters)
{
string result = string.Empty;
string parameterString = string.Join(
",", parameters.Select(i => i.ParameterName));
result = string.Format(
"{0} {1}", storedProcedureName, parameterString);
return result;
}
CreateParameter
public static SqlParameter CreateParameter(string parameterName, object value, SqlDbType dbType)
{
SqlParameter param = new SqlParameter(parameterName, dbType);
param.Value = value;
param.Value = value ?? (object)DBNull.Value;
return param;
}
GetCashInItemsParameters
public static IList<SqlParameter> GetCashInItemsParameters(string storedProcedureName)
{
IList<SqlParameter> parameters = new List<SqlParameter>();
try
{
parameters.Add(CreateParameter(
"#Year", 2019, SqlDbType.Int));
parameters.Add(CreateParameter(
"#Month", 3, SqlDbType.Int));
parameters.Add(CreateParameter(
"#FromDate", "2019-03-01", SqlDbType.Date));
parameters.Add(CreateParameter(
"#ToDate", "2019-03-31", SqlDbType.Date));
parameters.Add(CreateParameter(
"#CashCentreId",1, SqlDbType.Int));
parameters.Add(CreateParameter(
"#CustomerId", 2, SqlDbType.Int));
parameters.Add(CreateParameter(
"#CurrencyId", 1, SqlDbType.Int));
}
catch (Exception ex)
{
}
return parameters;
}
ExecuteStoredProcedureForDataRetrieve
public IList<T> ExecuteStoredProcedureForDataRetrieve<T>(string sqlQuery, params object[] parameters) where T : class
{
return db.Database.SqlQuery<T>(sqlQuery, parameters).ToList();
}
This is what i get as result
enter image description here
I tried with object , DataTable , DataSet. But it didnt work either. The project Im working on is using Repository. So Cannot use Traditional ADO.net
Three things:
You misspelled inv.uspMonthendProces
You are outputting a parameter, rather than parameter.value for the results.
The column that the parameter belongs to is not identified.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter
SqlParameter(String, SqlDbType, Int32, String)
Initializes a new instance of the SqlParameter class that uses the parameter name, the SqlDbType, the size, and the source column name.

Memory Cache .Net Core Not Persisting Values

I have a .NET Core 2.1 application. In Startup.cs configuration method, I use:
services.AddDbContext<ApplicationDbContext>(options =
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...
services.AddMemoryCache();
Then in my controller:
public class DropDownListController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IMemoryCache _memoryCache;
private const string ProvidersCacheKey = "providers";
private const string AgenciesCacheKey = "agencies";
public DropDownListController(ApplicationDbContext context, IMemoryCache memoryCache )
{
_context = context;
_memoryCache = memoryCache;
}
}
and in the controller also, the method to get the dropdownlist:
public JsonResult GetProvider()
{
IEnumerable<DropDownListCode.NameValueStr> providerlist;
if (_memoryCache.TryGetValue(ProvidersCacheKey, out providerlist))
{
return Json(providerlist);
}
else
{
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddDays(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList();
_memoryCache.Set(ProvidersCacheKey, result);
return Json(result);
}
}
When I set a breakpoint on the line:
return Json(providerlist);
I see the ProvidersCacheKey is in the _memoryCache, but it has no value.
What happened to the data?
When I do a Quick Watch on _memoryCache, I can see the DbContext object was destroyed. But how can that be, the code works fine but the cache object does not have the data I saved to it.
Any help would be appreciated.
The method to get providers is:
public IEnumerable<NameValueStr> GetProviderList()
{
var providerlist = (from a in _context.AgencyProvider
where a.Provider == a.AgencyId
select new NameValueStr
{
id = a.Provider,
name = a.Name
});
return providerlist.Distinct();
}
Adding "ToList()" in the calling method worked:
MemoryCacheEntryOptions cacheExpirationOptions = new MemoryCacheEntryOptions();
cacheExpirationOptions.AbsoluteExpiration = DateTime.Now.AddMinutes(30);
cacheExpirationOptions.Priority = CacheItemPriority.Normal;
DropDownListCode um = new DropDownListCode(_context);
var result = um.GetProviderList().ToList();
_memoryCache.Set(ProvidersCacheKey, result);
return Json(result);
All credit goes to Steve Py… Thank you sir!

RuntimeBinderException: Convert type System.Threading.Tasks.Task<object> to string

I do an example with signalR. But it doesn't function because of one mistake.
The one mistake (can not convert type system.threading.tasks.task< object> to string) is in this line:
return context.Clients.All.RecieveNotification(simple);
It is at the bottom of the code you can see below.
Below you see the method I wrote. There I do a connection with the database and get the content with a command/query.
Then a few checks and also SqlDependency.
public string SendNotifications()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "SELECT eintrag FROM [dbo].[simple_column]";
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
DataTable dt = new DataTable();
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
var reader = command.ExecuteReader();
dt.Load(reader);
if (dt.Rows.Count > 0)
{
simple = dt.Rows[0]["eintrag"].ToString();
}
}
}
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
return context.Clients.All.RecieveNotification(simple);
}
And here I use the function:
var notifications = $.connection.notificationHub;
notifications.client.recieveNotification = function (simple) {
// Add the message to the page.
$('#dbMessage').text(simple);
};
I hope you can help me.
Thanks.