Entity Framework and LINQ: Is there anyway to auto reflect the renamed entity in LINQ query - linq

I was trying to change the table names in the entity model or database but the old names are already use in many places in the application. Is there any way to auto reflect renamed entities or tables in the LINQ query or code.
Let say I have tables tblDepartment, tblEmployee and tblEmployeeDepartment. These tables are used in the code(LINQ) on many places. I like to change these tables names to Department, Employee and EmployeeDepartment. So, is there anyway to auto reflect name in LINQ or code when I change table names either using Database First or Model First approach.
P.S. The application is based on .Net 3.5

Working With linq and Entity Framework plus excel reports|Enjoy
public static string strMessage = "";
public SchoolEntities dbContext;
public string login(string strUsername, string strPassword)
{
dbContext = new SchoolEntities();
var linqQuery = from User in dbContext.People
where User.FirstName == strUsername && User.LastName == strPassword
select User;
if (linqQuery.Count() == 1)
{
strMessage = "Good";
}
else
{
strMessage = "Bad";
}
return strMessage;
}
public Object LoadPersonDetails()
{
dbContext = new SchoolEntities();
//DataTable dtPerson = new DataTable();
var linqQuery = from users in dbContext.People
select users;
//List<Person> Users = linqQuery.ToList();
//dtPerson = linqQuery.ToList();
return linqQuery;
}
public void InsertPerson(string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
dbContext = new SchoolEntities();
Person NewPerson = dbContext.People.Create();
NewPerson.LastName = strLName;
NewPerson.FirstName = strFName;
NewPerson.HireDate = Convert.ToDateTime(strHireDate);
NewPerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.People.Add(NewPerson);
dbContext.SaveChanges();
}
public void DeleteUser(int intPersonID)
{
//dbContext = new SchoolEntities();
using (dbContext = new SchoolEntities())
{
Person Person = dbContext.People.Where(c => c.PersonID == intPersonID).FirstOrDefault();
if (Person != null)
{
dbContext.People.Remove(Person);
dbContext.SaveChanges();
}
}
}
public void ModifyPerson(int intPersonID, string strLName, string strFName, string strHireDate, string EnrollmentDate)
{
var UpdatePerson = dbContext.People.FirstOrDefault(s => s.PersonID == intPersonID);
UpdatePerson.LastName = strLName;
UpdatePerson.FirstName = strFName;
UpdatePerson.HireDate = Convert.ToDateTime(strHireDate);
UpdatePerson.EnrollmentDate = Convert.ToDateTime(EnrollmentDate);
dbContext.SaveChanges();
}
private Excel.Application XApp = null; //Creates the Excel Document
private Excel.Workbook XWorkbook = null; //create the workbook in the recently created document
private Excel.Worksheet XWorksheet = null; //allows us to work with current worksheet
private Excel.Range XWorkSheet_range = null; // allows us to modify cells on the sheet
public void Reports()
{
dbContext = new SchoolEntities();
var linqQuery = (from users in dbContext.StudentGrades
group users by new { users.EnrollmentID, users.CourseID, users.StudentID, users.Grade }
into UserGroup
orderby UserGroup.Key.CourseID ascending
select new { UserGroup.Key.EnrollmentID, UserGroup.Key.CourseID, UserGroup.Key.StudentID, UserGroup.Key.Grade }).ToList();
var RatingAverage = dbContext.StudentGrades.Average(r => r.Grade);
var GradeSum = dbContext.StudentGrades.Sum(r => r.Grade);
/*var linqQuery = (from users in dbContext.StudentGrades
orderby users.CourseID descending
select users).ToList();*/
//Array Motho = linqQuery.ToArray();
XApp = new Excel.Application();
XApp.Visible = true;
XWorkbook = XApp.Workbooks.Add(1);
XWorksheet = (Excel.Worksheet)XWorkbook.Sheets[1];
//Create column headers
XWorksheet.Cells[2, 1] = "EnrollmentID";
XWorksheet.Cells[2, 2] = "CourseID";
XWorksheet.Cells[2, 3] = "StudentID";
XWorksheet.Cells[2, 4] = "Grade";
//XWorksheet.Cells[2, 5] = "Enrollment Date";
int row = 3;
foreach (var Mothos in linqQuery)
{
XWorksheet.Cells[row, 1] = Mothos.EnrollmentID.ToString();
XWorksheet.Cells[row, 2] = Mothos.CourseID.ToString();
XWorksheet.Cells[row, 3] = Mothos.StudentID.ToString();
XWorksheet.Cells[row, 4] = Mothos.Grade.ToString();
row++;
}
int rows = linqQuery.Count();
XWorksheet.Cells[rows + 4, 3] = "Grades Average";
XWorksheet.Cells[rows + 4, 4] = RatingAverage.Value.ToString();
XWorksheet.Cells[rows + 5, 3] = "Grades Sum";
XWorksheet.Cells[rows + 5, 4] = GradeSum.Value.ToString();
//XWorkSheet_range.ColumnWidth = 30;
//XWorksheet.Cells.AutoFit();
}

Working with xml | add, modify and delete xml data
string conn = "E:/School/Development Sftware/2014/ReadWriteUpdateDeleteXML/DataService/Profiles.xml";
public string InsertProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
XmlElement subRoot = xmlDoc.CreateElement("Profile");
//add first name
XmlElement appendedElementFname = xmlDoc.CreateElement("FirstName");
XmlText xmlTextFname = xmlDoc.CreateTextNode(fname.Trim());
appendedElementFname.AppendChild(xmlTextFname);
subRoot.AppendChild(appendedElementFname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add last name
XmlElement appendedElementLname = xmlDoc.CreateElement("LastName");
XmlText xmlTextLname = xmlDoc.CreateTextNode(lname.Trim());
appendedElementLname.AppendChild(xmlTextLname);
subRoot.AppendChild(appendedElementLname);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add phone
XmlElement appendedElementPhone = xmlDoc.CreateElement("Phone");
XmlText xmlTextPhone = xmlDoc.CreateTextNode(phone.Trim());
appendedElementPhone.AppendChild(xmlTextPhone);
subRoot.AppendChild(appendedElementPhone);
xmlDoc.DocumentElement.AppendChild(subRoot);
//add gender
XmlElement appendedElementGender = xmlDoc.CreateElement("Gender");
XmlText xmlTextGender = xmlDoc.CreateTextNode(gender.Trim());
appendedElementGender.AppendChild(xmlTextGender);
subRoot.AppendChild(appendedElementGender);
xmlDoc.DocumentElement.AppendChild(subRoot);
xmlDoc.Save(conn);
return "Profile Saved";
}
public DataSet LoadXML()
{
DataSet dsLog = new DataSet();
dsLog.ReadXml(conn);
return dsLog;
}
public string DeleteProfile(string fname)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
//XmlNode nodeToDelete = xmlDoc.SelectSingleNode("/Profiles/Profile[#FirstName=" + fname + "]");
//if (nodeToDelete != null)
//{
// nodeToDelete.ParentNode.RemoveChild(nodeToDelete);
//}
//xmlDoc.Save("C:/Users/Shazzy/Documents/Visual Studio 2010/Projects/ReadWriteUpdateDeleteXML/DataService/Profiles.xml");
//return "Deleted";
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.ParentNode.RemoveChild(node);
}
}
xmlDoc.Save(conn);
return "Deleted";
}
public string ModifyProfile(string fname, string lname, string phone, string gender)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(conn);
foreach (XmlNode node in xmlDoc.SelectNodes("Profiles/Profile"))
{
if (node.SelectSingleNode("FirstName").InnerText == fname)
{
node.SelectSingleNode("FirstName").InnerText = fname;
node.SelectSingleNode("LastName").InnerText = lname;
node.SelectSingleNode("Phone").InnerText = phone;
node.SelectSingleNode("Gender").InnerText = gender;
}
}
xmlDoc.Save(conn);
return "Updated";
}

Working with edm and Excel-grouped report
public void Function_Create_Sales()
{
DBContext = new PubsEntities();
var linqStores = from Sales in DBContext.sales
orderby Sales.stor_id
select Sales;
var lstStore = linqStores.ToList();
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlBook = xlApp.Workbooks.Add(1);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
int GroupTotal = 0;
int GrandTotal = 0;
int ExcelRow = 5;
string intTemp = lstStore[0].stor_id;
xlSheet.Cells[4, 1] = lstStore[0].stor_id;
//Create column headers
xlSheet.Cells[1, 1] = "Sales Grouped By Store";
xlSheet.Cells[3, 1] = "Group header";
xlSheet.Cells[3, 2] = "Store ID";
xlSheet.Cells[3, 3] = "Order Number";
xlSheet.Cells[3, 4] = "Order Date";
xlSheet.Cells[3, 5] = "Quantity";
xlSheet.Cells[3, 6] = "payments";
xlSheet.Cells[3, 7] = "title ID";
for (int count = 0; count < lstStore.Count; count++)
{
if (intTemp == lstStore[count].stor_id)
{
xlSheet.Cells[ExcelRow, 2] = lstStore[count].stor_id.ToString();
xlSheet.Cells[ExcelRow, 3] = lstStore[count].ord_date.ToString();
xlSheet.Cells[ExcelRow, 4] = lstStore[count].qty.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].payterms.ToString();
xlSheet.Cells[ExcelRow, 5] = lstStore[count].title_id.ToString();
ExcelRow++;
GroupTotal++;
GrandTotal++;
}
else
{
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
intTemp = lstStore[count].stor_id;
xlSheet.Cells[ExcelRow, 1] = lstStore[count].stor_id;
count--;
GroupTotal = 0;
ExcelRow++;
}
}
xlSheet.Cells[ExcelRow, 5] = "Total for: " + intTemp + " = " + GroupTotal.ToString();
ExcelRow++;
xlSheet.Cells[ExcelRow, 5] = "Grand Total = " + GrandTotal.ToString();
xlSheet.Rows.Columns.AutoFit();
}

Related

format export to excel using closedxml with Title

I am exporting to excel using closedxml my code is working fine, but i want to format my exported excel file with a title, backgroundcolour for the title if possible adding image.
private void button4_Click(object sender, EventArgs e)
{
string svFileName = GetSaveFileName(Convert.ToInt32(comboBox1.SelectedValue));
DataTable dt = new DataTable();
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dt.Columns.Add(col.HeaderText);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataRow dRow = dt.NewRow();
foreach (DataGridViewCell cell in row.Cells)
{
dRow[cell.ColumnIndex] = cell.Value;
}
dt.Rows.Add(dRow);
}
//if (!Directory.Exists(folderPath))
//{
// Directory.CreateDirectory(folderPath);
//}
if (svFileName == string.Empty)
{
DateTime mydatetime = new DateTime();
SaveFileDialog objSaveFile = new SaveFileDialog();
objSaveFile.FileName = "" + comboBox1.SelectedValue.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx";
objSaveFile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
objSaveFile.FilterIndex = 2;
objSaveFile.RestoreDirectory = true;
string folderpath = string.Empty;
Cursor.Current = Cursors.WaitCursor;
if (objSaveFile.ShowDialog() == DialogResult.OK)
{
Cursor.Current = Cursors.WaitCursor;
FileInfo fi = new FileInfo(objSaveFile.FileName);
folderpath = fi.DirectoryName;
int rowcount = 0;
int sheetcount = 1;
int temprowcount = 0;
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt,comboBox1.Text.ToString() + sheetcount.ToString());
ws.Row(1).Height=50;
//ws.FirstRow().Merge();
ws.Row(1).Merge();
//ws.Row(1).Value = comboBox1.Text.ToString();
//ws.Row(1).Cell(1).im
ws.Row(1).Cell(1).Value = comboBox1.Text.ToString();
ws.Row(1).Cell(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Row(1).Cell(1).Style.Alignment.Vertical=XLAlignmentVerticalValues.Center;
ws.Row(1).Cell(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Row(1).Cell(1).Style.Font.FontColor = XLColor.White;
ws.Row(1).Cell(1).Style.Font.FontSize = 21;
ws.Row(1).Cell(1).Style.Font.Bold = true;
ws.Column(1).Merge();
ws.Column(1).Style.Fill.BackgroundColor = XLColor.Red;
ws.Cell(2, 2).InsertTable(dt);
wb.SaveAs(fi.ToString());
//wb.SaveAs(folderpath + "\\" + comboBox1.SelectedItem.ToString() + "_" + mydatetime.ToString("ddMMyyhhmmss") + ".xlsx");
//rowcount = 0;
//sheetcount++;
//}
}
//}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}
else
{
Cursor.Current = Cursors.WaitCursor;
string folderpath = string.Empty;
folderpath = Properties.Settings.Default.ODRSPath + "\\" + svFileName;
using (XLWorkbook wb = new XLWorkbook())
{
//DateTime mydatetime = new DateTime();
wb.Worksheets.Add(dt, comboBox1.SelectedItem.ToString());
wb.SaveAs(folderpath);
}
MessageBox.Show("Report (.xlxs) Saved Successfully.");
}
}

Bind List to GridviewComboboxcolumn in telerik radgrindview (winform)

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 am trying to join 3 tables below is the code

var result = (from p in db.push_notifications
join nu in db.notification_recievers on p.id equals nu.push_notification_id
join nt in db.notification_types on p.notification_type_id equals nt.id
where (p.id == pushNotificationId && p.send_criteria == criteria && nu.delete_flag == false && p.delete_flag == false && nt.delete_flag == false)
select new NotificationList
{
conferenceId = p.conference_id,
pushNotificationId = p.id,
notificationId = nt.id,
notificationType = nt.notification_type,
nottificationDate = p.created_dt_tm,
criteria = (int)p.send_criteria,
notificationMessage = p.notification_msg,
userEmail=null,
userInterests = **getInterestNamesByPushNotificationId(p.id)**,
userEvents=null
}).Distinct();
public string getInterestNamesByPushNotificationId(int id)
{
string interests = string.Empty;
var query = from i in db.interests
join pn in db.notification_recievers
on i.id equals pn.interest_id
where pn.push_notification_id == id && pn.delete_flag == false
select new
{
name = i.name
};
foreach (var intr in query.Distinct())
{
if (interests == "")
{
interests = intr.name;
}
else
{
interests = interests + ", " + intr.name;
}
}
return interests;
}
this is throwing me error
LINQ to Entities does not recognize the method 'System.String
getInterestNamesBy PushNotification(Int32)' method, and this method
cannot be translated into a store expression.
The Entity Framework is trying to execute your LINQ clause on the SQL side, obviously there is no equivalent to 'getInterestNamesBy PushNotification(Int32)' from a SQL perspective.
You need to force your select to an Enumerable and then reselect your object using the desired method.
Not ideal but something like this should work - (not tested this so be nice).
var result = (from p in db.push_notifications
join nu in db.notification_recievers on p.id equals nu.push_notification_id
join nt in db.notification_types on p.notification_type_id equals nt.id
where (p.id == pushNotificationId && p.send_criteria == criteria && nu.delete_flag == false && p.delete_flag == false && nt.delete_flag == false)
select new { p=p, nu = nu, nt = nt }).AsEnumerable().Select( x => new NotificationList()
{
conferenceId = x.p.conference_id,
pushNotificationId = x.p.id,
notificationId = x.nt.id,
notificationType = x.nt.notification_type,
nottificationDate = x.p.created_dt_tm,
criteria = (int)x.p.send_criteria,
notificationMessage = x.p.notification_msg,
userEmail=null,
userInterests = getInterestNamesByPushNotificationId(x.p.id),
userEvents=null
}).Distinct();
i have done it this way
In my model
using (NotificationService nService = new NotificationService())
{
modelView = nService.DetailsOfNotifications(pushNotificationId, criteriaId).Select(x => new NotificationViewModelUI(x.conferenceId, x.pushNotificationId, x.notificationId, x.notificationType, x.nottificationDate, x.criteria, x.notificationMessage, x.userEmail, nService.getInterestNamesByPushNotificationId(x.pushNotificationId), nService.getIEventTitlesByPushNotificationId(x.pushNotificationId))).ToList();
}
public NotificationViewModelUI(int conferenceId, int pushNotificationId, int notificationId, string notificationType, DateTime dateTime, int criteria, string nMessage, string emailId = null, string interestNames = null, string eventTitles = null)
{
this.conferenceId = conferenceId;
this.pushNotificationId = pushNotificationId;
this.notificationId = notificationId;
this.notificationType = notificationType;
this.notificationDate = dateTime;
this.sendCriteria = (NotificationCriteria)criteria;
this.notificationMessage = nMessage;
this.emailId = NotificationCriteria.SpecificUser.Description() +"... "+ emailId;
this.interestNames = NotificationCriteria.UserByInterests.Description() + "... " + interestNames;
this.eventTitles = NotificationCriteria.UserByEvents.Description() + "... " + eventTitles;
}

Optimize queries for Union, Except, Join with LINQ and C#

I have 2 objects (lists loaded from XML) report and database (showed bellow in code) and i should analyse them and mark items with 0, 1, 2, 3 according to some conditions
TransactionResultCode = 0; // SUCCESS (all fields are equivalents: [Id, AccountNumber, Date, Amount])
TransactionResultCode = 1; // Exists in report but Not in database
TransactionResultCode = 2; // Exists in database but Not in report
TransactionResultCode = 3; // Field [Id] are equals but other fields [AccountNumber, Date, Amount] are different.
I'll be happy if somebody could found time to suggest how to optimize some queries.
Bellow is the code:
THANK YOU!!!
//TransactionResultCode = 0 - SUCCESS
//JOIN on all fields
var result0 = from d in database
from r in report
where (d.TransactionId == r.MovementID) &&
(d.TransactionAccountNumber == long.Parse(r.AccountNumber)) &&
(d.TransactionDate == r.MovementDate) &&
(d.TransactionAmount == r.Amount)
orderby d.TransactionId
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount,
TransactionResultCode = 0
};
//*******************************************
//JOIN on [Id] field
var joinedList = from d in database
from r in report
where d.TransactionId == r.MovementID
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount
};
//Difference report - database
var onlyReportID = report.Select(r => r.MovementID).Except(joinedList.Select(d => d.TransactionId));
//TransactionResultCode = 1 - Not Found in database
var result1 = from o in onlyReportID
from r in report
where (o == r.MovementID)
orderby r.MovementID
select new TransactionList()
{
TransactionId = r.MovementID,
TransactionAccountNumber = long.Parse(r.AccountNumber),
TransactionDate = r.MovementDate,
TransactionAmount = r.Amount,
TransactionResultCode = 1
};
//*******************************************
//Difference database - report
var onlyDatabaseID = database.Select(d => d.TransactionId).Except(joinedList.Select(d => d.TransactionId));
//TransactionResultCode = 2 - Not Found in report
var result2 = from o in onlyDatabaseID
from d in database
where (o == d.TransactionId)
orderby d.TransactionId
select new TransactionList()
{
TransactionId = d.TransactionId,
TransactionAccountNumber = d.TransactionAccountNumber,
TransactionDate = d.TransactionDate,
TransactionAmount = d.TransactionAmount,
TransactionResultCode = 2
};
//*******************************************
var qwe = joinedList.Select(j => j.TransactionId).Except(result0.Select(r => r.TransactionId));
//TransactionResultCode = 3 - Transaction Results are different (Amount, AccountNumber, Date, )
var result3 = from j in joinedList
from q in qwe
where j.TransactionId == q
select new TransactionList()
{
TransactionId = j.TransactionId,
TransactionAccountNumber = j.TransactionAccountNumber,
TransactionDate = j.TransactionDate,
TransactionAmount = j.TransactionAmount,
TransactionResultCode = 3
};
you may try something like below:
public void Test()
{
var report = new[] {new Item(1, "foo", "boo"), new Item(2, "foo2", "boo2"), new Item(3, "foo3", "boo3")};
var dataBase = new[] {new Item(1, "foo", "boo"), new Item(2, "foo22", "boo2"), new Item(4, "txt", "rt")};
Func<Item, bool> inBothLists = (i) => report.Contains(i) && dataBase.Contains(i);
Func<IEnumerable<Item>, Item, bool> containsWithID = (e, i) => e.Select(_ => _.ID).Contains(i.ID);
Func<Item, int> getCode = i =>
{
if (inBothLists(i))
{
return 0;
}
if(containsWithID(report, i) && containsWithID(dataBase, i))
{
return 3;
}
if (report.Contains(i))
{
return 2;
}
else return 1;
};
var result = (from item in dataBase.Union(report) select new {Code = getCode(item), Item = item}).Distinct();
}
public class Item
{
// You need also to override Equals() and GetHashCode().. I omitted them to save space
public Item(int id, string text1, string text2)
{
ID = id;
Text1 = text1;
Text2 = text2;
}
public int ID { get; set; }
public string Text1 { get; set; }
public string Text2 { get; set; }
}
Note that you need to either implement Equals() for you items, or implement an IEqualityComparer<> and feed it to Contains() methods.

Error in View when i try use inherit Linq magic

I try make table where i keep children-parent data. Ofc root of parents is "0" and here in table can by many roots. When i try make this work i got error.
Unable to create a constant value of type 'Projekty03.ViewsModels.ParagrafViewModel'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root" });
var _paragrafparent2 = from pr in paragrafRepository.All
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragraf = from par in paragrafRepository.All
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa
};
return View(paragraf);
}
I believe is sht wrong with my poor magic LINQ think. How resolve this ?
Ok here is a answer for my own question. Im sure is not a pretty solution but ...
public ViewResult Index()
{
List<ParagrafViewModel> _paragrafparent = new List<ParagrafViewModel>();
_paragrafparent.Add(new ParagrafViewModel { ParagrafID = 0, ParagrafNazwa = "Root", ParagrafCzynny=false, });
var _paragrafparent2 = from pr in paragrafRepository.AllIncluding(paragraf => paragraf.WniosekPodzial)
orderby pr.ParagrafID
select new ParagrafViewModel
{
ParagrafID = pr.ParagrafID,
ParagrafNazwa = pr.ParagrafNazwa,
ParagrafParent = pr.ParagrafParent,
ParagrafCzynny = pr.ParagrafCzynny,
ParagrafWplyw = pr.ParagrafWplyw,
WniosekPodzialNazwa = pr.WniosekPodzial.WniosekPodzialNazwa
};
var _paragrafparent3 = _paragrafparent.Concat(_paragrafparent2).AsEnumerable();
var paragrafModel = from par in _paragrafparent3
join rodzic_p in _paragrafparent3
on par.ParagrafParent equals rodzic_p.ParagrafID
orderby par.ParagrafParent, par.ParagrafID
select new ParagrafViewModel
{
ParagrafID = par.ParagrafID,
ParagrafNazwa = par.ParagrafNazwa,
ParagrafParent = par.ParagrafParent,
ParagrafCzynny = par.ParagrafCzynny,
ParagrafWplyw = par.ParagrafWplyw,
ParagrafParentNazwa = rodzic_p.ParagrafNazwa,
WniosekPodzialNazwa = par.WniosekPodzialNazwa
};
return View(paragrafModel);
}

Resources