System.InvalidOperationException at Dapper - asp.net

i'm going to use dapper as my ORM in asp .net project.
So the problem is, i'm going to execute my procedure to return get data by Id.
If the Id is not exist, the error appeard like this
Sequence contains no elements
is there any solution to prevent the error by using dapper? because the other solution using entity framework.
here's my code
var SP_Name = "SP_GetSupplierById";
parameters.Add("#Id", Id);
var getSupplierById = connection.QuerySingle<Supplier>(SP_Name,parameters,commandType:CommandType.StoredProcedure);
return getSupplierById;
and here's my procedure
CREATE PROCEDURE SP_GetSupplierById
#Id int
AS
SELECT * from TB_M_Supplier where id = #Id;
RETURN 0
Thanks for your help

QuerySingle asserts that there is exactly one row returned; not zero, not multiple. If zero is acceptable, then you can use QuerySingleOrDefault - and check for the default, which will be null in the case of reference types (classes). QuerySingleOrDefault only asserts that there aren't multiple rows; zero is fine.
So
var getSupplierById = connection.QuerySingleOrDefault<Supplier>(SP_Name,parameters,commandType:CommandType.StoredProcedure);
return getSupplierById; // todo: consider null

Related

Spring JDBC Dynamic Query into Map of objects

I have to dynamically execute queries which will come from database.The query has dynamic fields,which needs to be converted into map as key value pairs and send to view.For ex
one query may return only one fields and other may return more than two field of multiple rows.I have to write code in such way that it will work for n no.of fields and return it as map using spring jdbc.
Spring offers two ways to solve your problem.
Approach 1: use queryForList method from JdbcTemplate class. this will return List of Map populated by column names as key , and DB record as value. you have to manualy iterate over the list. each map object inside the list represents a single row in resultset.
example :
List<Map<String, Object>> result = jdbcTemplate.queryForList(query, new Object[]{123});
Iterator items = result.iterator();
while(items.hasNext()){
Map<String, Object> row = (Map<String, Object>) items.next();
System.out.println(row);
}
Approach 2 : this dosen't exactly match your requirements, but little faster than the first approach also more coding involved. you can use queryForRowSet method.
SqlRowSet rowSet = jdbcTemplate.queryForRowSet(query, new Object[]{3576});
int columnCount = rowSet.getMetaData().getColumnCount();
System.out.println(columnCount);
while(rowSet.next()){
for(int id =1 ; id <= columnCount ; id ++){
System.out.println(rowSet.getString(id)) ;
// your custom logic goes here
}
}

NHibernate: adding calculated field to query results

I have inherited an ASP.NET website built on NHibernate, with which I have no experience. I need to add a calculated field based on a column in a related table to an existing query. In SQL, this would be done easily enough using a correlated subquery:
select
field1,
field2,
(select count(field3) from table2 where table2.table1ID = table1.ID) calc_field
from
table1
where
[criteria...]
Unfortunately, of course, I can't use SQL for this. So in reality, I have three related questions:
What is the best way to trace through the web of interfaces, base classes, etc used by NHibernate in order to pinpoint the object where I need to add the field?
Having located that object, what, if anything, has to be done besides adding a public property to the object corresponding to the new field?
Are there any NHibernate-specific considerations with regard to referencing a related object in a query?
Here is the existing code that performs the search:
public INHibernateQueryable<C> Search(ISearchQuery query, string sortField)
{
_session = GetSession();
var c = _session.Linq<C>();
c.Expand("IP");
c.Expand("LL");
c.Expand("LL.Address");
c.Expand("LL.Address.City");
c.Expand("LL.Address.City.State");
c.Expand("LL.Address.City.County");
c.Expand("CE");
c.Expand("IC");
c.Expand("AR");
c.Expand("ER");
c.Expand("Status");
var res = _SearchFilters
.Where(x => x.ShouldApply(query))
.Aggregate(c, (candidates, filter) => (INHibernateQueryable<C>) filter.Filter(candidates, query));
res = SortSearch(res, sortField);
return res;
}
I appreciate any advice from experienced Hibernators.
Thanks,
Mike
If you are only interested in returning a query containing a computed value, you can still call a stored procedure in NHibernate and map the results to a POCO in the same way as you map a table for CRUD operations; obviously read-only instead of updatable.
Have a look at the ISession.CreateSQLQuery method; I can post an example from one of my projects if you need one.

EF4 throws NotSupported exception when it (imho) shouldn't

OK, this thing just puzzles me.
I have a table, say Users, with columns UserID, Name, etc. Have an object mapped to it using CTP5. So now I want to test it, and do the following:
List<User> users = new List();
// Some init code here, making say 3 users.
using (UsersDbContext)
{
// insert users
}
So far so good, works fine.
Now I want to see if the records match, so I select the users back using the following code.
using (UsersDbContext dbc = UsersDbContext.GetDbContext())
{
List<Users> usersRead = dbc.Users.Where(x => x.ID >= users[0].ID && x.ID <= users[users.Count - 1].ID).ToList();
}
This throws and exception:
System.NotSupportedException: LINQ to
Entities does not recognize the method
'User get_Item(Int32)' method, and
this method cannot be translated into
a store expression.
EF has difficulties seeing that I'm just asking to return an int in Users[0].ID ?
If I replace a call to users[0].ID with a straight int - works fine.
I get what it's trying to do, but I thought it should be pretty easy to check if the method belongs to .NET or Sql Server ?
You are trying to access an indexer in an EF expression, which doesn't translate to an SQL query. You'll have to move the parameters outside the query like this:
int first = users[0].ID;
int last = users[users.Count - 1].ID;
List<Users> usersRead = dbc.Users.Where(x => x.ID >= first && x.ID <= last).ToList();

in asp.net dynamic date, how to use partial method to validate fields aganist data in database

i want to make sure all product names are unique so i tried to do the following.
but it is causing an infinity loop at the lambda expression.
public partial class Product
{
partial void OnProductNameChanging(string value)
{
using(var ctx = new MyEntityContext()){
var val = value;
var item = ctx.Products.Where(o=>o.ProductName == val).FirstOrDefault();
if(item != null)
throw new ValidationException("Product Name existed.");
}
}
}
i'm using asp.net 4.0 with dynamic data and entity framework.
Why don't you set it up on database level and handle exeption in case if product name already exists?
I am not too familiar with EF, but you should get the changeset and compare values. That is, for the Product Entity and in the case of the the changeset having an Update, compare the EXISTING value with NEW, and change the new in the case of duplication.
Here's how to get changeSet in EF :
http://davidhayden.com/blog/dave/archive/2005/11/16/2570.aspx
the comparison and value must be called before any context.SubmitChanges();
Hope this helps.

How to return multi-table join value from BLL

This question is regarding the ASP.NET webservice that i am creating using the DAL-BLL architecture for my final school project.
I have a stored procedure, which is a select query with an inner join for 2 tables. Hence the stored procedure returns multi-table value. One of my DAL tableAdapter methods accesses this stored procedure. How do i retrieve the return value in the BLL? Do i have to create a class structure similar to the one supposed to be returned by the stored proc? or is there a direct way to achieve the same? Help greatly appreciated. Please let me know if someone needs code applet to get a better understanding. Thanks
Here is some more information:
I am using the SQL dataset (.xsd) in DAL. So i have a datatable called "Insurance", which has a tableAdapter. One of the queries in the adapter references to a stored procedure, which has an inner join. So my SP looks like:
ALTER PROCEDURE dbo.GetInsurancesPaged
(
#startRowIndex int,
#maximumRows int,
#patientID int
)
AS
select * from
(
SELECT Insurance.insuranceID, Insurance.memberID, Insurance.groupID, Insurance.accountType, Insurance.comments, Insurance.patient, Insurance.company, InsuranceCompany.companyID, InsuranceCompany.companyName, InsuranceCompany.address, InsuranceCompany.phone, InsuranceCompany.fax, ROW_NUMBER() over (order by Insurance.dateModified DESC) as ROWRANK
FROM Insurance INNER JOIN InsuranceCompany ON Insurance.company = InsuranceCompany.companyID
WHERE Insurance.patient = #patientID
)
AS DataWithRowNumbers
WHERE ROWRANK > #startRowIndex AND ROWRANK <= (#startRowIndex + #maximumRows)
So this SP returns a datatable which will be a combination of the 2 tables in the inner join. Please correct me if i am wrong.
Now in my BLL, i have:
[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
public mySys.InsuranceDataTable GetInsurancesPaged(int startRowIndex, int maximumRows, int patientID)
{
return insAdapter.GetInsurancesPaged(startRowIndex, maximumRows, patientID);
}
where insAdapter is an instance of insuranceTableAdapter
This gives an error on execution. I can execute the SP successfully, so i think the problem is only bcz i am trying to return a wrong datatable from the BLL.
Please help me solve this.
If using ADO .Net dataset. The wizard will definetly create a table for the same. now from the dataaccess layer, do the following steps
1. Create a object of dataset. (DLL)
Private YourCustomeDataSetDatatable DataAccess()
{
YourCustomDataSet ds = new YourCustomDataSet(); // also called strongly typed dataset
YourCustomeDataSetDatatable dt = ds.YourCustomeDataSetDatatable ()
YourCustomeDataSetTableAdapter ta = new ds.YourCustomeDataSetTableAdapter (); // table adapter that will be invoked
ta.Fill(dt); // or if you have set to return only you can also use GetData()
}
2. Now in business layer
Private YourCustomeDataSetDatatable DataAccess()
{
// create a object of DLL.
MyDAL myDal = new MyDAL ();
return myDal.DataAccess();
}
Catch this on your UI page by following the creating object of BLL and call the method. Here in BLL you can also do various operations to lowered the codes in you ui and keeping it clean from various manipulations.
Found a solution :)
Finally got it working.
I created a new table adapter using the Dataset designer, and called the SP as one of the queries there. The datatable thus created, has all the fields (from Insurance and InsuranceCompany) included. Now, ASP.NET can detect that the return type is the newly created datatable.
Works like a charm.
If there is a better way to solve this, please comment.
Thank you all for your time.

Resources