I have ListView like this
<asp:ListView ID="ListView1" ItemType="test.Project"
SelectMethod="ListView1_GetData" runat="server">
I am trying to set the select method to a stored procedure using EF. the select method like this
public IQueryable<Test.Project> ListView1_GetData()
{
using (DREntities2 db=new DREntities2())
{
return db.GetLatestProjects().AsQueryable();
}
}
I get this error:
Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)
If I remove the .AsQueryable(), I get this error:
Cannot implicitly convert type 'System.Data.Objects.ObjectResult' to 'System.Linq.IQueryable
Here is the definition of the GetLastestProjects_Result as returned by DREntities2 .GetLatestProjects():
public partial class GetLatestProjects_Result
{
public int ProjectID { get; set; }
public string Title { get; set; }
public string ShortDescr { get; set; }
public string Full_Descr { get; set; }
public int ProCatID { get; set; }
public bool Marquee { get; set; }
}
Your stored procedure is returning ObjectResult<Test.GetLatestProjects_Result> and you are trying to convert it to IQueryable<Test.Project>. To do this you need to convert using the Linq Select method. Assuming Test.GetLatestProjects_Result and Test.Project have the same properties:
public IQueryable<Test.Project> ListView1_GetData()
{
using (DREntities2 db=new DREntities2())
{
return db.GetLatestProjects().Select(p => new Test.Project
{
ProjectId = p.ProjectId,
Title = p.Title,
ShortDescr = p.ShortDescr,
Full_Descr = p.Full_Descr,
ProCatID = p.ProCatID,
Marquee = p.Marquee
}).AsQueryable();
}
}
A little late to the game, but others may be able to do the following. Assuming that Test.Project is an EntityType, in the Model Browser change the return type of your stored procedure in the EF Model to Test.Project instead of the default GetLatestProjects_Result "complex type" that is created.
Then, in your query you can take the result to a typed list, then call AsQueryable on the result.
Here is an example that calls an SP named GetAllRequestsByWorkflowState which returns TravelRequestSummaryView entities:
private IQueryable<TravelRequestSummaryView> GetApprovalRequests(int approvalState)
{
IQueryable<TravelRequestSummaryView> trsv = null;
try
{
var res = db.GetAllRequestsByWorkflowState(approvalState)
.ToList<TravelRequestSummaryView>();
trsv = res.AsQueryable();
}
catch (Exception ex)
{
sqlTraceManager.WriteTraceIf(ex, User.Identity.Name);
}
return trsv;
}
Related
little assistance here with my query using dapper, been getting error Message = "ORA-00936: missing expression\n" on my query. I would like to know what am I missing here?
public class LocationDto
{
public int LocationId { get; set; }
public int RouteId { get; set; }
public string StartTime { get; set; }
public string Location { get; set; }
}
// Query Below
using (OracleConnection connection = new OracleConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
try {
var x = connection.QueryAsync<LocationDto>("Select ROUTE_ID as RouteId, SCHEDULE_STOP as Location, START_TIME as StartTime From SCHEDULE WHERE ROUTE_ID = #Id", new { input.RouteId }).Result.ToList();
}
catch (Exception ex)
{
}
}
Firstly with Oracle queries you need to use : instead of # to denote a parameter placeholder.
Then secondly this code:
new { input.RouteId }
will produce an object with a property called RouteId.
This RouteId does not match the name of the parameter in your query, which is Id. They need to match, otherwise there's no way for the database to bind the parameter to the correct input value.
You can either
change the Sql query:
WHERE ROUTE_ID = :RouteId
OR
change the C#:
new { Id = input.RouteId }
and use :Id in the SQL.
It doesn't really matter which, the important thing is that the names match.
So I'm trying to store a record in the databse using dapper. I'm passing an object to the method where I have my query to store the recorde. Let me be more clear. Below is my model :
public class Foo
{
public long FooId { get; set; }
public Guid Foo2ID { get; set; }
public string Status { get; set; }
public Person Person { get; set; } = new Person();
}
public class Person
{
public string Type { get; set; }
public string Character { get; set; }
public DateTime Test { get; set; }
}
And this is my query :
public async Task<ActionResult> Create(Foo f)
{
using (var connection = _dbAccess.CreateConnection())
{
var sqlStatement = #"
INSERT INTO ReportRequests
(FooId
,Foo2Id
,Person
,Status)
VALUES
(#FooId
#,Foo2Id
#,Person
#,Status)";
await connection.ExecuteAsync(sqlStatement, f);
};
return Ok();
}
I'm trying to save a json in the Person column in the database. But I get this error :
The member x of type x cannot be used as a parameter value
Can anyone please give me an idea on how I can approach to this problem. It would be very helpful.
Thank you a lot :)
enter code hereFirst of all, you should consider whether you can use LINQ-like queries with dapper. It makes it both more readable and avoids having issues like that.
Back to your problem, from the code you posted it looks like you've misplaced the comas after the # symbol #,Foo2Id :
(#FooId
#,Foo2Id
#,Person
#,Status)
It should be:
(#FooId
#Foo2Id,
#Person,
#Status)
I have a bunch of classes generated by EF that are simple tables and have similar structures:
public class Contact
{
public int ID { get; set; }
public string Description { get; set; }
}
public class Member
{
public int ID { get; set; }
public string Description { get; set; }
}
I've also got a method for returning an object of a specified type:
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
What I want to do is something like this:
public ActionResult GetAll(string ClassType) // ClassType will be the name of one of the classes above
{
Object LookupType = GetInstance<Object>(ClassType);
List<LookupType> AllList = new List<LookupType>();
AllList = repo.GetAll<LookupType>().ToList<LookupType>(); // some generic method that will return a list;
}
This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list. However, neither of these work either:
List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
Both cause an error - "Using generic type List requires 1 type argument".
Is there a proper way to do this? Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?
Try using the CreateInstance method
SomeObject someObject = new SomeObject();
Type type = someObject.GetType();
Type listType = typeof(List<>).MakeGenericType(new [] { type });
IList list = (IList)Activator.CreateInstance(listType);
You cannot do it with C#!!
Compiler must to know the parameter type.
In that maybe you would like to accomplish, interfaces will help you
public class Contact: IIdDescription
{
public int ID { get; set; }
public string Description { get; set; }
}
public class Member: IIdDescription
{
public int ID { get; set; }
public string Description { get; set; }
}
public interface IIdDescription
{
int ID { get; set; }
string Description { get; set; }
}
public ActionResult GetAll(string type)
{
var AllList = new List<IIdDescription>();
if(type == Member.GetType().Name)
AllList = repo.Set<Member>().Cast<IIdDescription >().ToList();
if(type == Contact.GetType().Name)
AllList = repo.Set<Contact>().Cast<IIdDescription >().ToList();
...
}
and into your view use interface as model, something like
#model IEnumerable<IIdDescription>
If you don't know the type ahead of time maybe using a list of dynamic objects can help.
var item = GetInstance<Contact>("Namespace.Contact");
var items = new List<dynamic>();
items.Add(item);
You can then access the types like so...
Contact contact = items[0];
Just be aware that using dynamic can be expensive.
I've been tasked to add a page to an API that we didn't build but are tasked to work on. The API is using C# MVC5. I don't really know MVC5, and but I'm attempting to keep the same design pattern that the rest of the API is using. I have to add functionality that will allow a user on the front end to upload a file to a server that will be processed for inserting into a SQL Server DB. This functionality will also return a list of all the files names and status of the imported files from a table in the DB.
The issue I'm having is converting a Datetime to a string in the LINQ query that is pulling the list of files.
I've attempted to try using this answer LINQ convert DateTime to string, but with no luck.
This is what I have so far, I've marked the line that is causing the issue:
[Route("ImportLogs", Name ="GetImportLogs")]
[HttpGet]
[ResponseType(typeof(List<IHttpActionResult>))]
public IHttpActionResult GetImportLogs()
{
var query =
from dbitem in db.ImportLogs
orderby dbitem.import_log_id
select new ImportLogDto()
{
Id = dbitem.import_log_id,
FileName = dbitem.import_file_name,
ImportTimeStamp = dbitem.import_timeStamp,
ImportStatus = dbitem.import_status,
ImportMessage = dbitem.import_message
};
query.ToList()
.Select(o => new ImportLogDto
{
Id = o.Id,
FileName = o.FileName,
ImportMessage = o.ImportMessage,
ImportStatus = o.ImportStatus,
ImportTimeStamp = o.ImportTimeStamp.ToString() //PROBLEM LINE
});
return Ok(query);
}
The error that I'm getting is
Cannot implicitly convert type 'string' to 'System.DateTime'
What am doing wrong? Any help would be appreciated. TIA.
EDIT:
Here is the DTO:
public class ImportLogDto
{
public int Id { get; set; }
public string FileName { get; set; }
public DateTime ImportTimeStamp { get; set; }
public string ImportStatus { get; set; }
public string ImportMessage { get; set; }
}
You are trying to assign a string into a DateTime so you get that exception. If you want to cast it to a string change your model as follows:
public class ImportLogDto
{
public int Id { get; set; }
public string FileName { get; set; }
public string ImportTimeStamp { get; set; } // Changed type
public string ImportStatus { get; set; }
public string ImportMessage { get; set; }
}
And then your query:
var query = (from dbitem in db.ImportLogs
orderby dbitem.import_log_id
select new {
Idbitem.import_log_id,
dbitem.import_file_name,
dbitem.import_timeStamp, // Still DateTime
dbitem.import_status,
dbitem.import_message
}).AsEnumerable(); // Retrieved from Database
.Select(o => new ImportLogDto
{
Id = o.import_log_id,
FileName = o.import_file_name,
ImportMessage = o.import_message,
ImportStatus = o.import_status,
ImportTimeStamp = o.import_timeStamp.ToString() // Changes to string
});
If you wnat to change the format of the DateTime for the API then then use its overload of ToString and specify a format:
ImportTimeStamp = o.ImportTimeStamp.ToString("dd/MM/yyyy HH24:MI:ss")
For more on the overload read: Custom Date and Time Format Strings
Your types are already DateTime, and since these types are tied to the backing data* you probably shouldn't change them. But where you return the values on the API you can really return anything you want. So an anonymous type could be a quick solution:
.Select(o => new // <--- notice no type definition here
{
Id = o.Id,
FileName = o.FileName,
ImportMessage = o.ImportMessage,
ImportStatus = o.ImportStatus,
ImportTimeStamp = o.ImportTimeStamp.ToString()
})
The compiler will know based on the type returned by .ToString() that you want ImportTimeStamp to be a string. You can then add formatters to .ToString() to customize the output however you like.
*If your DTO isn't actually tied to the database then you can change the type there from DateTime to string, of course. It's not really clear from the context of the code shown whether these are data DTOs or application DTOs.
This is my first question here and I'm new to WPF/MVVM.
What I'm trying to do is display a multi-column listview that holds the results returned from a stored procedure.
I'm doing my best to implement MVVM and this is where I'm having trouble.
I have a model (SL_ID is the PK and not nullable in the database):
public class mJob_Select_OrderList
{
public int SL_ID { get; set; }
public string E32JobNumber { get; set; }
public string E32_CLIENT { get; set; }
public string SL_DESCRIPTION { get; set; }
public string E32_DESCRIPTION { get; set; }
}
and then I have a view model:
public class vmJob_Select : vmMain
{
#region Members
Models.mJob_Select _mJobSelectSettings;
public SLEVEN_CLASS.dbSLEVENDataContext _dc;
#endregion
#region Constructors
public vmJob_Select()
{
_dc = new SLEVEN_CLASS.dbSLEVENDataContext();
_mJobSelectSettings = new Models.mJob_Select { EnvironmentID = 1 };
//EnvironmentList
var dsEnvironmentList = (from el in _dc.vw_EnvironmentLists orderby el.ENV_ID select new mJob_Select_Environment { ENV_ID = el.ENV_ID, Environment = el.Environment, IMAGE_RESOURCE = el.IMAGE_RESOURCE });
EnvironmentList = new ObservableCollection<mJob_Select_Environment>(dsEnvironmentList);
//Orders List
var dsSLEVENOrders = _dc.get_SLORDER_List(SelectedEnvironmentID).ToList();
SelectOrderList = new List<mJob_Select_OrderList>(dsSLEVENOrders);
}
#endregion
#region Properties
public Models.mJob_Select mJobSelectSettings { get { return _mJobSelectSettings; } set { _mJobSelectSettings = value; } }
public int SelectedEnvironmentID { get { return mJobSelectSettings.EnvironmentID; } set { if (mJobSelectSettings.EnvironmentID != value) { mJobSelectSettings.EnvironmentID = value; RaisePropertyChanged("EnvironmentID"); } } }
public ObservableCollection<mJob_Select_Environment> EnvironmentList { get; set; }
public List<mJob_Select_OrderList> SelectOrderList { get; set; }
}
So basically EnvironmentList is pulled from a view in the database and I can populate an ObservableCollection successfully. The SelectedOrderList is the result of a stored procedure and I'm trying to load this result into a list object of some sort.
The error I'm getting is
Cannot convert from 'System.Collections.Generic.List' to 'int'
I was able to implement this successfully in the code behind on the view but I'm trying to adhere to MVVM and making my ViewModel do the work.
using (SLEVEN_CLASS.dbSLEVENDataContext dbSLEVEN = new SLEVEN_CLASS.dbSLEVENDataContext())
{
var dsSLEVENOrders = dbSLEVEN.get_SLORDER_List(intENVID);
lvSlevenJobs.ItemsSource = dsSLEVENOrders;
lvSlevenJobs.SelectedValuePath = "SL_ID";
}
I've been searching and trying to figure this out for awhile now and I've tried to implement some solutions that I've found here and there to no avail. One involved looping through the IResult and adding each row to the model another suggested building a more complex linq query instead of a stored procedure. None of these options are out of the question. Is there a generally accepted method for performing this task?
Thanks in advance to any answers/suggestions you can provide!
//EDIT//
I believe I've found my solution. I was trying to return my SPROC results to a model that I created but when using LINQ a Model is created automatically called Procedure Name + 'Result'.
I declared my list to utilize the 'Result' model like so:
public List<get_SLORDER_ListResult> SelectOrderList { get; set; }
List<get_SLORDER_ListResult> lstSLEVENOrders = _dc.get_SLORDER_List(SelectedEnvironmentID).ToList<get_SLORDER_ListResult>();
SelectOrderList = new List<get_SLORDER_ListResult>(lstSLEVENOrders);
I then bound my ListView to SelectOrderList.