MVC Query Result no accept null values - asp.net-mvc

enter image description here Function ListarTipoMascotas() As JsonResult
Dim db As New LQTestDataContext
Dim Listado = From tipomascota In db.TipoMascotas
Where tipomascota.BHABILITADO = 1
Select New With {
.Id = tipomascota.IIDTIPOMASCOTA,
.Nombre = tipomascota.NOMBRE
}
Return New JsonResult With {.Data = Listado,
.JsonRequestBehavior = JsonRequestBehavior.AllowGet
}
End Function
This is my function in VB. MVC , is work fine, but when I have null values the LINQ sent a error.
I'm working with LINQ for my conexion database,
My question is, how I can to do, to this result I can return null values without any problem.
Thank you. I read you.

Related

Entity Framework 6 - Passing Table Valued Parameter to Table Valued Function, returning IQueryable

I want to call a Table Valued Function from entity framework, and have it return an IQueryable. The code I have is:
// Defines table-valued function, which must return IQueryable<T>.
[Function(FunctionType.TableValuedFunction, nameof(ufnGetContactInformation), Schema = dbo)]
public IQueryable<ContactInformation> ufnGetContactInformation(
[Parameter(DbType = "int", Name = "PersonID")]int? personId)
{
ObjectParameter personIdParameter = personId.HasValue
? new ObjectParameter("PersonID", personId)
: new ObjectParameter("PersonID", typeof(int));
return this.ObjectContext().CreateQuery<ContactInformation>(
$"[{nameof(this.ufnGetContactInformation)}](#{nameof(personId)})", personIdParameter);
}
However, I also want to be able to pass into the TVF a Table Valued Parameter (so I can pass a list of Id's into the TVF). I've found code that can do this using a DataTable which references the user-defined type I have in the db, eg:
var dt = new DataTable();
dt.Columns.Add("Id");
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
var idList = new SqlParameter("idList", SqlDbType.Structured);
warnings.Value = dt;
warnings.TypeName = "dbo.udt_idList";
entities.ExecuteStoredProcedure("usp_TableValuedFunc", idList);
The problem is, the second code uses SQLParameter, and the first code uses ObjectParameter. It appears that ObjectParameter won't allow for user-defined-types to be supplied, and any code EF uses that accepts SQLParameter won't allow me to return an IQueryable from a TVF. Any ideas, am I missing something?

Asp.net MVC 4 Database Query returning sql query.

I am trying to query my database to get a specific data from my database. however when I convert the query to string it doesn't return the select value, instead it returns the whole SQL Query in a string. I am stumped on why this is happening
public ActionResult StudiedModules()
{
Model1 studiedModules = new Model1();
List<StudiedModulesModel> listModules = new List<StudiedModulesModel>();
using (EntityOne context = new EnitityOne())
{
foreach(var module in context.StudiedModules){
studiedModules.School = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.School).ToString();
studiedModules.Subject = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.Subject).ToString();
}
}
var data = listModules;
return View(data);
}
Calling ToString() on an Entity Framework Linq query like that will in fact return the SQL Query. So as it's written, your code is doing exactly what you wrote it to do.
If you want to select the first result from the IQueryable<T>, then you need to call First() before your ToString(). So, try changing
studiedModules.School = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.School).ToString();
studiedModules.Subject = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.Subject).ToString()
to
studiedModules.School = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.School).First().ToString();
studiedModules.Subject = context.ModuleDatas.Where(p=>p.ModuleCode == module.ModuleCode).Select(u=>u.Subject).First().ToString()
There are a whole lot more methods available depending on what you're trying to accomplish. If you want to get a list, use ToList(), or as Uroš Goljat pointed out, you can get a comma-separated list of values using the Aggregate( (a, b)=> a + ", " + b) method.
How about using Aggregate( (a, b)=> a + ", " + b) instead of ToString().
Regards,
Uros

How can I check results for select statement in MVC?

Hi this is the SP I have :
USE [Tracker_Entities]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[uspHub]
#id int
AS
BEGIN
SELECT DISTINCT table1.UID, table1.url, Scope.ID
FROM table1 INNER JOIN
Scope ON table1.UID = Scope.newBrand
WHERE (table1.value = 0) AND (Scope.ID = #id)
ORDER BY table1.url
END
GO
When i run this SP in sql server by passing ID as parameter i am getting expected result. Now I need to check this SP in mvc. This is the way I am calling this SP in my MVC :
using (var ctx = new database_Entities())
{
int ID = 122;
ctx.uspHub(ID);
ctx.SaveChanges();
}
But when I put breakpoint in using statement and check for results, it is not displaying any results. I am struggling here for long time and i am not getting proper solution for this. So what are the steps in MVC to check results for SP which has select statements??
Update :
I got solution for this after using tolist. Now i am getting three results in list and i need to grab one result that is URL and pass it as input parameter.
My code :
int ID = 413;
var x = ctx.uspdHub(ID).ToList();
Here x has 3 results. I need to take one result from it.I tried doing x. but it doesn't show results after i type dot. How can i achieve this??
You have to Get the result into proper model/object.
List<YourEntity> model;
using (var ctx = new database_Entities())
{
int ID = 122;
model = ctx.uspHub(ID).toList();
//ctx.SaveChanges(); - no need to call SaveChanges
// - as you are not updating anything
}
Go through this article if you need more info. Call Stored Procedure From Entity Framework (The code above will work anyways...)
use...
using (var ctx = new database_Entities())
{
int ID = 122;
var result = ctx.uspHub(ID);
}
and add a break after the result to see whats in the result variable. Obviously, the sope of result will need to be moved, but I'm only showing here how you can see the data returned.
Try to use something like this:
using (var dataContext= new database_Entities())
{
int ID = 122;
SomeEntity[] result = dataContext.Database.SqlQuery<SomeEntity>("[dbo].[uspHub] #id",new SqlParameter("#id", ID)).ToArray();
}
It is good for me. I have used ORM EntityFramework to connect with DB.

Can't able to access data by LINQ query

[HttpPost]
public ActionResult Playlist(String ID)
{
long playid=Convert.ToInt64(ID);
var q = from client in Clients
join m in db.Playlists on client.ClientId equals m.ClientId
join meta in db.ContentMetaDatas on m.PlaylistId equals meta.PlaylistId
where m.PlaylistId.Equals(playid)
orderby m.PlaylistId descending
select new SimpleViewModel
{
ID = m.PlaylistId,
Live = false,
Expired = meta.ContentMetaDataExpiryDateTime != null,
Details = m.PlaylistShortDescription,
ImageUrl = meta.ContentMetaDataImage,
Title = m.PlaylistTitle
};
return Json(q.ToPage(p, "ID desc"), JsonRequestBehavior.DenyGet);
}
As shown in the above code of controller I want to fetch data those are returned in JSON data format & used in view.
But As I have to convert the string into long datatype,
what can I do for getting data. Is there anything wrong in the above code??

assign nullable objects for returning IQueryable

I am returning IQueryable<Customer> to the other method for some querying operations. The return method looks like:
return from cust in _dbCustList
select new Customer
{
CustomerId = cust.Customer_Id,
FirstName= cust.First_Name,
LastName= cust.Last_Name,
DOB= cust.Date_Of_Birth,
LoginTime = cust.Login_Time ?? new TimeSpan(0, 0, 0);
};
In the above result, cust.Login_Time is nullable property.
When i try to query the above result, it throws an error:
Method 'System.TimeSpan GetTimeSpan(System.Nullable`1[System.TimeSpan])' has no supported translation to SQL.
How to solve this error?
I would query into an anonymous type and then map the result to your business object in-memory:
var q = from cust in _dbCustList
select new
{
cust.Customer_Id,
cust.First_Name,
cust.Last_Name,
cust.Date_Of_Birth,
cust.Login_Time
};
return from cust in q.AsEnumerable()
select new Customer
{
CustomerId = cust.Customer_Id,
FirstName= cust.First_Name,
LastName= cust.Last_Name,
DOB= cust.Date_Of_Birth,
LoginTime = cust.Login_Time ?? TimeSpan.Zero;
};
Why do you use the null- check?
When you remove the null check the written query gets translated into a SQL query and will be executed. Now you have the result you can do any magic you want...

Resources