SQL Query to Linq Query Result into complex object - c#

I have SQL Query ready, and that I want its result into a complex SQL object. I want to use Linq to achieve the result.
public class VMPackageList
{
public string PackageName { get; set; }
public string ShortTitle { get; set; }
}
public class VMPackageItenary
{
public string PackageName { get; set; }
public string Day { get; set; }
public string Title { get; set; }
public string Detail { get; set; }
}
public class VMPackageHighlight
{
public string PackageName { get; set; }
public string Highlightname { get; set; }
public string HighlightDesc { get; set; }
}
The expected result in below class
public class VMPackageDetails
{
public VMPackageList vmPackage { get; set; }
public VMPackageItenary[] vmPackageItenary { get; set; }
public VMPackageHighlight[] vmPackageHighlights { get; set; }
}
Below are the SQL query and its result, the same way I want to get into
SQL table data query
This is my result query
I had tried with below code to achieve but I did not get success
var packages = packageRepository.Table;
var highlights = packageHighlightRepository.Table;
var itenaries = packageItenaryRepository.Table;
var data = (from package in packages
join highlight in highlights on package.PackageName equals highlight.PackageName
join iteratory in itenaries on package.PackageName equals iteratory.PackageName //&&
where package.PackageName == packageName //&& highlight.PackageName equals iteratory.PackageName
select new VMPackageDetails
{
// vmPackage = package
}).ToList();
Can anyone help me to get the result?

Related

Listview/Datagrid binding from query generated list

So I have a query that returns values from multiple tables with a left join.
But I can't seem to get the data from left join table.
public IEnumerable<TipsTricks> GetTipsTricks()
{
using(var connection = new SqlConnection(Connection.Instance.ConnectionString))
{
return connection.Query<TipsTricks>(#"SELECT tt.ID, cat.Omschrijving, tt.Info, tt.Onderwerp, tt.Firma FROM tblTipsAndTricks as tt
LEFT JOIN tblTT_Categorieen as cat on cat.Id = tt.CategorieID ");
}
}
I then do in code behind to bind it to Datagrid.ItemsSource:
public void initialize()
{
List<TipsTricks> tipstricks = DatabaseManager.Instance.TipsTricksRepository.GetTipsTricks().ToList();
DgTipsTricks.ItemsSource = tipstricks;
}
Class TipsTricks
public class TipsTricks
{
public int Id { get; set; }
public string Info { get; set; }
public string Onderwerp { get; set; }
public string Firma { get; set; }
string Omschrijving { get; set; }
}
Also tried the binding in de XAML without succes.
So I would like a column in the datagrid showing the content of cat.Omschrijving from the left join table tblTT_Categorieen.
Thanks!
Try making the property string Omschrijvin "public"
as shown below
public class TipsTricks
{
public int Id { get; set; }
public string Info { get; set; }
public string Onderwerp { get; set; }
public string Firma { get; set; }
public string Omschrijving { get; set; }
}

Using Dapper with multiple inner joins

I am trying to use Dapper with the following sql string but I am unable to get it work:
string groupsStringDetailed = "SELECT SUSERGROUP.NAME, SUSERGROUP.DESCRIPTION, SPROGRAMS.PROGRAMNAME, SOBJECTS.NAME FROM ((SIDE.SADMIT SADMIT " +
"INNER JOIN SIDE.SOBJECTS SOBJECTS ON (SADMIT.PROGRAMID=SOBJECTS.PROGRAMID) AND (SADMIT.OBJECTID=SOBJECTS.ID)) " +
"INNER JOIN SIDE.SUSERGROUP SUSERGROUP ON SADMIT.GROUPID=SUSERGROUP.GROUPID) " +
"INNER JOIN SIDE.SPROGRAMS SPROGRAMS ON SOBJECTS.PROGRAMID=SPROGRAMS.ID " +
"WHERE SUSERGROUP.NAME NOT LIKE '%REPORT' ORDER BY SUSERGROUP.NAME, SPROGRAMS.PROGRAMNAME";
I have the following model classes:
public class SAdmit
{
public int GROUPID { get; set; }
public int OBJECTID { get; set; }
public int PROGRAMID { get; set; }
}
public class SObjects
{
public int ID { get; set; }
public int PROGRAMID { get; set; }
public string NAME { get; set; }
}
public class SPrograms
{
public int ID { get; set; }
public string PROGRAMNAME { get; set; }
}
public class SUserGroup
{
public int GROUPID { get; set; }
public string NAME { get; set; }
public string DESCRIPTION { get; set; }
public int VWLISTDEPTH { get; set; }
public int WDNBDAYHISTORY { get; set; }
public string RPDIRECTORY { get; set; }
public string SENDEREMAIL { get; set; }
public int CONNECTION_TIMEOUT { get; set; }
public int APPROVALSTATUS { get; set; }
}
I createad a custom group class hoping to map easier those models:
public class CustomSGroup
{
public SUserGroup Group { get; set; }
public SPrograms Programs { get; set; }
public SObjects Objects { get; set; }
}
I am trying to use Dapper to get results I want like this:
var output = await cnn.QueryAsync<CustomSGroup, SAdmit, SObjects, SPrograms, CustomSGroup>(groupsStringDetailed, (g, a, o, p) =>
{
a.PROGRAMID = o.PROGRAMID;
a.OBJECTID = o.ID;
a.GROUPID = g.Group.GROUPID;
o.PROGRAMID = p.ID;
return g;
}, splitOn: "PROGRAMID, OBJECTID, GROUPID, NAME");
but I am unable to see the big picture and what I am doing wrong because it throws an exception
"When using the multi-mapping APIs ensure you set the splitOn param if you have keys other than Id\r\nParameter name: splitOn"
I am able to use Dapper with a simpler (one) inner join sql string, but this one I cannot get it work.
I reviewed the code and I've come to the conclusion that you simply are not including the fields you need to split on. Add the following fields to your query (perhaps adding distinct labels for the types that share similar field names.
PROGRAMID, OBJECTID, GROUPID, NAME

LINQ to Entities does not recognize the method ..., and this method cannot be translated into a store expression

My function is as on lambda expression
public IList<ent_Message> messageDetailsArray(decimal from,decimal to)
{
owncibai_ExamEntities db = new owncibai_ExamEntities();
var details = db.Messages.OrderBy(or=>or.mDate).Where(wh => (wh.userNumber==from && wh.messageTo==to) || (wh.messageTo==from && wh.userNumber==to)).Select(a => new ent_Message
{
isRead = a.isRead,
mDate = a.mDate,
Message1 = a.Message1,
messID = a.messID,
userNumber = a.userNumber,
messageTo=a.messageTo,
Name=a.User.First_Name+" "+a.User.Last_Name,
photo = (db.MessagePhotoes.Where(ph => ph.messID == a.messID).Select(b => new ent_MessagePhoto
{
msgPhoto=b.msgPhoto,
srl=b.srl
})).ToList()
}).ToList();
var update = db.Messages.Where(wh => wh.messageTo == from).ToList();
update.ForEach(a => a.isRead = true);
db.SaveChanges();
return details;
}
It works fine when I remove Photo parameter from list. While I add photo it is giving following error.
LINQ to Entities does not recognize the method 'System.Collections.Generic.List1[Entities.ent_MessagePhoto] ToList[ent_MessagePhoto](System.Collections.Generic.IEnumerable1[Entities.ent_MessagePhoto])' method, and this method cannot be translated into a store expression.
Entity class is as follows
public class ent_Message{
public decimal messID { get; set; }
public Nullable<decimal> userNumber { get; set; }
public Nullable<decimal> messageTo { get; set; }
public Nullable<System.DateTime> mDate { get; set; }
public string ip { get; set; }
public string Message1 { get; set; }
public Nullable<bool> isRead { get; set; }
public Nullable<decimal> parentID { get; set; }
public string Name { get; set; }
public IList<ent_MessagePhoto> photo { get; set; }
}
I am totally confused where I am wrong in photo...
Thanks in advance
This bit:
photo = (db.MessagePhotoes.Where(ph => ph.messID == a.messID).Select(b => new ent_MessagePhoto
{
msgPhoto=b.msgPhoto,
srl=b.srl
})).ToList() //<-right here
appears inside your outer Select clause. When the IQueryProvider tries to convert your outer Select statement to valid SQL, it will see an inner Select, which of course can be converted to SQL, but then it will hit the ToList() call and fail, because there is no equivalent in SQL.
If you want to perform some operations in your Select projection that can't be done in SQL, they need to be done against the query result set in-memory on the .NET application side. One common way to do this is to put a ToList() before your select statement - this will be interpreted as "send the Where and OrderBy parts to SQL, bring the full result set back into a List, then perform the Select projection".
ent_MessagePhoto must be in the class definition
public class ent_Message<ent_MessagePhoto>
{
public decimal messID { get; set; }
public Nullable<decimal> userNumber { get; set; }
public Nullable<decimal> messageTo { get; set; }
public Nullable<System.DateTime> mDate { get; set; }
public string ip { get; set; }
public string Message1 { get; set; }
public Nullable<bool> isRead { get; set; }
public Nullable<decimal> parentID { get; set; }
public string Name { get; set; }
public IList<ent_MessagePhoto> photo { get; set; }
}​
Thanks for your suggestion I resolved this issue. Issue was version only. I was using 5.x and updated to 6.x and working fine.

c#. EF entity sql. How to get entity with related objects?

I have made simple model for example.
public class Publisher
{
public int Id { get; set; }
public string Title { get; set; }
public Address Location { get; set; }
public virtual ICollection<Book> Books { get; set; }
}
public class Address
{
public string Country { get; set; }
public string City { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
}
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public int LanguageId { get; set; }
public int? PublisherId { get; set; }
}
I need to get publishers with related books. I know how to do it using linq to entities. Is it possible to solve a problem using entity sql?
public class CatalogContext : DbContext {...}
public List<Publisher> GetByCity(string city)
{
var result = new List<Publisher>();
string queryString;
queryString = String.Format(#"SELECT VALUE row(a,b)
FROM CatalogContext.Publishers AS a
join CatalogContext.Books AS b on a.Id = b.PublisherId
WHERE a.Location.City = '{0}'", city);
var rows = ((IObjectContextAdapter)_context).ObjectContext.CreateQuery<DbDataRecord>(queryString).ToList();
return ???
}
Query returns required data but it's List<DbDataRecord> - list of pairs <publisher, book>. How to translate it to list of publishers with filled navigation property "Books"?
Is it possible to write query which directly returns List<Publisher>?
you can do the following:
var result = ObjectContext.Publishers.Include("Books").Include("Locations")
.Where(c => c.Location.City = "SOME_CITY").Select(c => c);
Include - basically joins the table.
Then you can drill down to books by doing the following:
var test = result[0].Books;
Why are you using direct sql command instead of Entity Framework code style?

How to use selectmany in linq?

The following is my linq query
var meetingIndividualQuery = meetingsList.SelectMany(o => o.Attendies.Distinct().Where(x => x.CompanyId == company.CompanyId));
I have the following class
public class Meetings
{
public string IndustryCouncil { get; set; }
public string MeetingType { get; set; }
public string MeetingDescription { get; set; }
public string MeetingDate { get; set; }
public string MeetingHours { get; set; }
public string MeetingHourlyValue { get; set; }
public string MeetingTotal { get; set; }
public List<Individual> Attendies { get; set; }
}
With the above query I am getting the correct list of individaul but how I can I use the same query with the same condition to retrieve the list of Meetings. Can you please provide me any code
Following query will return list of meetings, which have at least one attendee with provided company id:
var query = meetingsList.Where(m => m.Attendies.Any(i => i.CompanyId == company.CompanyId));
You can also apply Distinct to Attendies before verifying Any

Categories

Resources