Here's my code. I want to save the list in a session variable for later authentication (it's a list of objects the user is authorized to access....) I get an error saying it cannot implictly convert System.Collections.Generic.List to 'System.collections.Generic.List. Help?
protected void Session_Start(object sender, EventArgs e)
{
string strUserName = User.Identity.Name;
string strShortUserName = strUserName.Replace("WINNTDOM\\", string.Empty).ToUpper();
System.Web.HttpContext.Current.Session["strShortUserName"] = strShortUserName;
System.Web.HttpContext.Current.Session["strUserName"] = strUserName;
List<string> authorizedObjects = new List<string>();
using (CPASEntities ctx = new CPASEntities())
{
var w = (from t in ctx.tblUsers
where (t.UserPassword == strUserName)
select t).FirstOrDefault();
if (!(w==null))
{
authorizedObjects = (from t in ctx.qryUserObjectAuthorization
where (t.UserPassword == strUserName)
select new { n = t.ObjectName }).ToList();
}
}
}
To generate that as a list of strings use
authorizedObjects = (from t in ctx.qryUserObjectAuthorization
where (t.UserPassword == strUserName)
select t.ObjectName).ToList();
authorizedObjects is List<string> but you're trying to use it as a List of anonymous type:
List<string> authorizedObjects = new List<string>();
(...)
authorizedObjects = (from t in ctx.qryUserObjectAuthorization
where (t.UserPassword == strUserName)
select new { n = t.ObjectName, i = t.ObjectID }).ToList()
Change your query to that:
authorizedObjects = (from t in ctx.qryUserObjectAuthorization
where (t.UserPassword == strUserName)
select t.ObjectName).ToList()
You are initializing a List<string> object but populating different object.
List<string> authorizedObjects = new List<string>();
select new { n = t.ObjectName, i = t.ObjectID } <--construct a class with these properties and initialize `List<WithNewClassName>`
Related
I have a generic List like
List<return> returnlist
class return
{
public string returnid {get; set;
...
public List<string> Vouchernumbers
}
I bind the returnlist to the telerik radgridview.
How can i bind the voucherlist to the GridviewComboboxcolumn for each row ?
I have bind the voucherlist to the combobox after radgridview_complete_binding.
You need to create the grid with columns and data
You need to add the combobox column, initialize it.. Please check you need to have a dataeditor in here
Assign the string to datasource
comboColumn.DataSource = new String[] { "Test1", "Test2"};
You can bind the collections too:
Binding list BindingList<ComboBoxDataSourceObject> list = new BindingList<ComboBoxDataSourceObject>();
ComboBoxDataSourceObject object1 = new ComboBoxDataSourceObject();
object1.Id = 1;
object1.MyString = "Test 1";
list.Add(object1);
ComboBoxDataSourceObject object2 = new ComboBoxDataSourceObject();
object2.Id = 2;
object2.MyString = "Test 2";
list.Add(object2);
colboCol2.DataSource = list;
radGridView1.Columns.Add(colboCol2);
create radcombobox and set datasource and add it to rad grid
eg :
GridViewComboBoxColumn col = new GridViewComboBoxColumn();
col.DataSource = DAL.ActiveDb.GetList<SalesRep>().ToList().OrderBy(x => x.RepName).Select(x => new { Id = x.Id, x.RepName });
col.DropDownStyle = RadDropDownStyle.DropDown;
col.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
col.DisplayMember = "RepName";
col.ValueMember = "Id";
col.FieldName = "RepId";
col.HeaderText = "Rep Name";
col.Width = 200;
//var t = gridColInfo.Where(x => x.ColumnName.ToLower() == "repid").FirstOrDefault();
//if (t != null)
//{
// col.Width = t.ColumnWidth;
//}
this.radGridBillwiseOpening.Columns.Add(col);
I created a list property in my model like so
public virtual List<String> listOfDays { get; set; }
then I converted and stored it in the list like this:
for (int i = 0; i < 30 i++)
{
var enrollment = new Enrollment();
enrollment.StudentID = id;
enrollment.listOfDays = searchString.ToList();
db.Enrollments.Add(enrollment);
db.SaveChanges();
}
I put a breakpoint here... enrollment.listOfDays = searchString.ToList(); ... and all is well. I see that the conversion was performed and I can see the values in listOfDays.
So I thought I would find a column in my database called listOfDays since I'm doing code first but the property is not there.
Then I thought I'd try accessing it anyway like this...
var classdays = from e in db.Enrollments where e.StudentID == id select e.listOfDays;
var days = classdays.ToList();
//here I get an error message about this not being supported in Linq.
Questions:
Why do you think the property was not in the database?
How can I post this array to my model then access it in a controller?
Thanks for any help.
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}
Thanks to Decker: http://forums.asp.net/members/Decker%20Dong%20-%20MSFT.aspx
Here’s how it works:
Using form collection here…
In [HttpPost]…
private void Update (FormCollection formCollection, int id)
for (int sc = 0; sc < theSelectedCourses.Count(); sc++)
{
var enrollment = new Enrollment();
enrollment.CourseID = Convert.ToInt32(theSelectedCourses[sc]);
enrollment.StudentID = id;
enrollment.listOfDays = formCollection["searchString"] ;//bind this as a string instead of a list or array.
Then in [HttpGet]…
private void PopulateAssignedenrolledData(Student student, int id)
{
var dayList = from e in db.Enrollments where e.StudentID == id select e;
var days = dayList.ToList();
if (days.Count > 0)
{
string dl = days.FirstOrDefault().listOfDays;
string[] listofdays = dl.Split(',');
ViewBag.classDay = listofdays.ToList();
}
Is it possible to use Dynamic Linq to run a query similar to:
Select a, b, a + b as c
from MyDataTable
I have an application where the user can enter SQL statements, the results of these statements are then assigned to a DataTable. There is also the option to derive a field based on other fields. (e.g. user can say field C = a + b, or field D = A*B+10 etc).
Ideally I would like to do something similar to:
string myCalc = "Convert.ToDouble(r.ItemArray[14])+Convert.ToDouble(r.ItemArray[45])";
var parameters = from r in dt.AsEnumerable()
select (myCalc);
What I want to do in this example is add the value of column 14 to column 45 and return it. It's up to the user to decide what expression to use so the text in the select needs to be from a string, I cannot hard code the expression. The string myCalc is purely for demonstration purposes.
You could do that using a Dictionary, and a DataReader and Dynamic Queries. Here is an example based in part in Rob Connery's Massive ORM RecordToExpando:
void Main()
{
string connString = "your connection string";
System.Data.SqlClient.SqlConnection conn = new SqlConnection(connString);
string statement = "SUM = EstimatedEffort + OriginalEstimate, Original = OriginalEstimate";
// Note: You should parse the statement so it doesn't have any updates or inserts in it.
string sql = "SELECT " + statement +" FROM Activities";
List<IDictionary<string, object>> results = new List<IDictionary<string, object>>();
conn.Open();
using(conn)
{
var cmd = new SqlCommand(sql, conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var dic = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
dic.Add(
reader.GetName(i),
DBNull.Value.Equals(reader[i]) ? null : reader[i]);
}
results.Add(dic);
}
}
foreach (var dicRow in results)
{
foreach (string key in dicRow.Keys)
{
Console.Write("Key: " + key + " Value: " + dicRow[key]);
}
Console.WriteLine();
}
}
Something like this:
void Main()
{
var dataTable = new DataTable();
dataTable.Columns.Add("a", typeof(double));
dataTable.Columns.Add("b", typeof(double));
dataTable.Rows.Add(new object[] { 10, 20 });
dataTable.Rows.Add(new object[] { 30, 40 });
string myCalc = "Convert.ToDouble(ItemArray[0]) + Convert.ToDouble(ItemArray[1])";
var query = dataTable.AsEnumerable().AsQueryable();
var result = query.Select(myCalc);
foreach (Double c in result)
{
System.Console.WriteLine(c);
}
}
I am having trouble to return an IEnumerable and IList, I cant do it!
I am using EF 4 with POCOs
Here's the whole method:
//public IList<Genre> GetGenresByGame(int gameId)
public IEnumerable<Genre> GetGenresByGame(int gameId)
{
using(var ctx = new XContext())
{
var results =
from t0 in ctx.GameGenres
join t1 in ctx.GenreCultureDetails on t0.GenreId equals t1.GenreId
where t0.GameId == gameId && t1.CultureId == _cultureId
select new Genre
{
GenreId = t0.GenreId,
GenreName = t1.GenreName
};
return results.ToList();
}
}
I have tried different ways that I have found on the net.. but can't make it work!
Question 2:
I saw a screencast with Julie something, saying that "You should always return an ICollection" when using EF4.
Any thoughts about that ?
BR
EDIT:
When I load the page in Debug-mode i get these errors: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. OR The entity or complex type 'XModel.Genre' cannot be constructed in a LINQ to Entities query.
Genre must not be a L2EF type. Try this:
public IEnumerable<Genre> GetGenresByGame(int gameId)
{
using(var ctx = new XContext())
{
var resultList =
from t0 in ctx.GameGenres
join t1 in ctx.GenreCultureDetails on t0.GenreId equals t1.GenreId
where t0.GameId == gameId && t1.CultureId == _cultureId
select new { t0.GenreId, t1.GenreName };
var genres = resultList.AsEnumerable().Select(o => new Genre
{
GenreId = o.GenreId,
GenreName = o.GenreName
});
return genres.ToList();
}
}
First an foremost if Genre is in the database you should select it? If you have FKs from Genre->GenreCultureDetails let me know and I can update the below, but from the looks of it you could do it like this:
using(var ctx = new XContext())
{
var results =
from g in ctx.Genre
join gcd in ctx.GenreCultureDetails on g.GenreId equals gcd.GenreId
where g.GameId == gameId && gcd.CultureId == _cultureId
select g;
return result.ToList();
}
Alternatively continue down your path select them into an annoynmous type, and then copy them. You can use select instead of convertall if you please.
IList<Genre> returnMe = Null;
using(var ctx = new XContext())
{
var results =
from t0 in ctx.GameGenres
join t1 in ctx.GenreCultureDetails on t0.GenreId equals t1.GenreId
where t0.GameId == gameId && t1.CultureId == _cultureId
select new
{
GenreId = t0.GenreId,
GenreName = t1.GenreName
};
returnMe = results.ToList().ConvertAll(x=>new Genre(){
GenreId = x.GenreId,
GenreName = x.GenreName
}
);
}
return returnMe;
this is the way i used to save record with linq: (my Q is below)
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee = (from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
oldEmployee.BirthDate = employee.BirthDate;
oldEmployee.WorkRole = employee.WorkRole;
oldEmployee.CurrentFlag = employee.CurrentFlag;
oldEmployee.HireDate = employee.HireDate;
...
db.Employees.InsertOnSubmit(oldEmployee);
}
else
{
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
}
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
my questions are:
a. are the if statements nesccery? why not to make the assigning without the
check?
mybe the if block take more cpu..
b. why to spearate the new record block and the update block?
when the record is new it will do
db.Employees.InsertOnSubmit(oldEmployee);
and then proceed with the update routine...
The way you're doing it the only reason you need the if statement is to new it up and insert it, so I would use the if statement just for that.
I would do this instead:
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee =
(from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
db.Employees.InsertOnSubmit(oldEmployee);
}
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
I also think there's a way to map one object's properties to the other, but it escapes me at the moment. It may not work for what you're trying to do anyway since it seems that you're doing some other things later anyway with the ModifiedDate and EmployeeID.