I am using LINQ and am having a hard time understanding how I can make new "domain model" classes work within LINQ while querying across tables. I am using Linq to SQL, and C# in .NET 3.5.
Suppose I want an Extended Client class:
public class ExtendedClient
{
public int ID { get; set; }
public string Name { get; set; }
public string strVal { get; set; }
}
and in my data layer, I want to populate this from two tables (dc is my DataContext):
public ExtendedClient getExtendedClient(int clientID)
{
var c = dc.GetTable<tClient>();
var cs = dc.GetTable<tClientSetting>();
var q = from client in c
join setting in cs
on client.ClientID equals setting.ClientID
where client.ClientID == clientID
select new ExtendedClient { client, setting.strValue };
return q;
}
I am trying to return the row in the table tClient plus one extra column in tClientSetting.
The annoying errors I get are :
Cannot initialize type 'ExtendedClient' with a collection initializer because it does not implement 'System.Collections.IEnumerable'
and
Cannot implicitly convert type 'System.Linq.IQueryable' to 'ExtendedClient'. An explicit conversion exists (are you missing a cast?)
I realize this is a basic error, but I cannot determine how BEST to implement the IEnumerable because I cannot find an example.
Do I have to do this every time I want a specialized object? Thanks in advance.
public ExtendedClient getExtendedClient(int clientID)
{
var c = dc.GetTable<tClient>();
var cs = dc.GetTable<tClientSetting>();
var q = from client in c
join setting in cs
on client.ClientID equals setting.ClientID
where client.ClientID == clientID
select new ExtendedClient { ID = client.ClientID, Name = client.Name, strVal = setting.strValue };
return q.Single();
}
You'll have to do a similar thing every time you need to return a specialized object. If you don't need to return it, you don't have to specify the type and you won't need a special class. You could use anonymous types:
from client in c
join setting in cs
on client.ClientID equals setting.ClientID
where client.ClientID == clientID
select new { ID = client.ClientID, Name = client.Name, strVal = setting.strValue };
Why do you use a special type for this?
I think you can do client.Settings.strValue if you setup the Client-Settings relationship to create a property Client.Settings (instead of Settings.Client). And as far as I remember such configuration is possible in LINQ.
Related
I am trying to concatenate IQueryable where T can be different types.
So ((IQueryable<Person>)people).Concant((IQueryable<Account>)accounts).
I have created a structure like so:
public struct PerformanceStructure
{
public Entity Entity { get; set; }
public Entity Performance { get; set; }
}
I am building dynamic queries that follow this template:
var result = context.Accounts.Where(a => a.id == 1).Select(s => new PerformanceStructure { Entity = s });
result = result.Concat(context.Person.Where(p => p.id = 1).Select(s => new PerformanceStructure {Entity = s});
Execution looks like this:
var list = result.Skip(pageSize * (pageNumber - )).Take(pageSize);
When executing the query, I get the error Types in Union or Concat have different members assigned
What can I do to resolve this error but retrieve the two objects from that database?
In the end I want to paginate the query (thus the skip/take) based on some order.
I recently started experimenting with Raw SQL using Entity Framework, and I prefer it in some cases.
I would like to know if there is a way to grab relational entities:
Dosnt work:
var personNo = context.Person.SqlQuery("SELECT * FROM `Person` LIMIT 1").FirstOrDefault();
foreach(var Number in personNo.Phone) {
//never iterates
}
Works (but LINQ-to-Entities which I dont want in this case):
var personNo = context.Person.FirstOrDefault();
foreach(var Number in personNo.Phone) {
//iterate twice as it contains in the db
}
I tried a couple of different queries including
SELECT * FROM `Person` LEFT JOIN `Phone` ON (`Person`.ID = `Phone`.PersonID) LIMIT 1
What is the correct way to write the query on to recieve the list of Phone numbers? Is this possible?
You can do SQL to entities. I prefer this way when I have joins and group bys in them, and don't have permission to create a view.
First, create a class and add properties with the same names as the returned columns.
public class PersonWithAddress
{
public int Id { get; set; }
public String Name { get; set; }
public String Address { get; set; }
}
And the C# with parameters
MyEntity db = new MyEntity();
String sqlQuery = #"
SELECT Id, Name, Address
FROM Person p
JOIN Address a
ON a.Id = p.Id
WHERE Name = #Name
AND Address = #Address
";
String searchName = "Joe";
String address = "123 Something Lane";
DbRawSqlQuery<PersonWithAddress> results = db.Database.SqlQuery<PersonWithAddress>(
sqlQuery,
new SqlParameter("#Name", searchName),
new SqlParameter("#Address", address)
);
foreach(PersonWithAddress a in results)
{
}
You can list as many parameters as you want.
Wow this question's 2 years old. I didn't even realize that.
I am trying to create a REST service using Nancy FX in a C# environment. I can easily do a Response.AsJson and it all looks good. But I want the response to omit any properties that are null.
I have not been able to figure out how to do this yet.
Could someone point to me towards a help document or a blog post somewhere, that explains how to do this.
Thanks,
JP
I would create a dynamic anonymous type and return that. So let's say you have a User object like this:
public class User
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
You want to pass back an instance of this type as a JSON response so you will have some code like this:
Get["/user/{userid}"] = parameters =>
{
var user = UserService.GetById(Db, (string)parameters.userid);
if (user == null) return HttpStatusCode.UnprocessableEntity;
return Response.AsJson(user);
};
But you don't want to return the User instance, instead you want to return an separate instance of a dynamic type that will only implement a property if the property value is not null for a given instance.
So I would suggest code something like this:
Get["/user/{userid}"] = parameters =>
{
var user = UserService.GetById(Db, (string)parameters.userid);
if (user == null) return HttpStatusCode.UnprocessableEntity;
dynamic userDTO = new ExpandoObject();
userDTO.Id = user.Id;
if (!string.IsNullOrEmpty(user.FirstName)) userDTO.FirstName = user.FirstName;
if (!string.IsNullOrEmpty(user.LastName)) userDTO.Lastname = user.LastName;
return Response.AsJson((ExpandoObject)userDTO);
};
Note 1
You don't need to test for the Id since that is implied by the successful return of the User instance from the database.
Note 2
You need to use a dynamic type so you can include ad hoc properties. The problem is that extension methods cannot accept dynamic types. To avoid this you need to declare it as an ExpandoObject but use it as a dynamic. This trick incurs a processing overhead but it allows you to cast the dynamic to an ExpandoObject when passing it in to the AsJson() extension method.
I will start by saying this may not be conceptually correct so I will post my problem also, so if someone can help with the underlying problem I won't need to do this.
Here is a simplified version of my model.
public class MenuItem
{
public int MenuItemId { get; set; }
public string Name { get; set; }
public virtual ICollection<Department> Departments { get; set; }
private ICollection<MenuSecurityItem> _menuSecurityItems;
public virtual ICollection<MenuSecurityItem> MenuSecurityItems
{
get { return _menuSecurityItems ?? (_menuSecurityItems = new HashSet<MenuSecurityItem>()); }
set { _menuSecurityItems = value; }
}
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
My underlying problem is that I want to select all MenuItems that belong to a Department (Department with DepartmentId = 1 for arguments sake) and also include all MenuSecurityItems.
I am unable to Include() the MenuSecurityItems as the MenuItems navigation collection is of type ICollection and doesn't support Include(). This also doesn't seem to work Department.MenuItems.AsQueryable().Include(m => m.MenuSecurityItems)
The way I "fixed" this issue was creating an entity for the many-to-many mapping table Code First creates.
public class DepartmentMenuItems
{
[Key, Column(Order = 0)]
public int Department_DepartmentId { get; set; }
[Key, Column(Order = 1)]
public int MenuItem_MenuItemId { get; set; }
}
I then was able to join through the mapping table like so. (MenuDB being my DBContext)
var query = from mItems in MenuDb.MenuItems
join depmItems in MenuDb.DepartmentMenuItems on mItems.MenuItemId equals depmItems.MenuItem_MenuItemId
join dep in MenuDb.Departments on depmItems.Department_DepartmentId equals dep.DepartmentId
where dep.DepartmentId == 1
select mItems;
This actually worked for that particular query... however it broke my navigation collections. Now EF4.1 is throwing an exception as it is trying to find an object called DepartmentMenuItems1 when trying to use the navigation collections.
If someone could either help me with the original issue or the issue I have now created with the mapping table entity it would be greatly appreciated.
Eager loading of nested collections works by using Select on the outer collection you want to include:
var department = context.Departments
.Include(d => d.MenuItems.Select(m => m.MenuSecurityItems))
.Single(d => d.DepartmentId == 1);
You can also use a dotted path with the string version of Include: Include("MenuItems.MenuSecurityItems")
Edit: To your question in comment how to apply a filter to the MenuItems collection to load:
Unfortunately you cannot filter with eager loading within an Include. The best solution in your particular case (where you only load one single department) is to abandon eager loading and leverage explicite loading instead:
// 1st roundtrip to DB: load department without navigation properties
var department = context.Departments
.Single(d => d.DepartmentId == 1);
// 2nd roundtrip to DB: load filtered MenuItems including MenuSecurityItems
context.Entry(department).Collection(d => d.MenuItems).Query()
.Include(m => m.MenuSecurityItems)
.Where(m => m.Active)
.Load();
This requires two roundtrips to the DB and two queries but it's the cleanest approach in my opinion which actually only loads the data you need.
Other workarounds are 1) either to apply the filter later in memory (but then you have to load the whole collection first from the DB before you can filter) or 2) to use a projection. This is explained here (the second and third point):
EF 4.1 code-first: How to order navigation properties when using Include and/or Select methods?
The examples in this answer are for ordering but the same applies to filtering (just replace OrderBy in the code snippets by Where).
I have been building a Motion Picture application to manage actors or "Talents". I have a TALENT table and a LANGUAGES table. I also have a TALENTLANGUAGES table that shows the many to many relationship between the two.
Here is the SQL i can write to show the different languages a given talent speaks.
Select t.TalentID, t.FirstName, tl.LanguageID, l.Name from Talent t
inner join TalentLanguage tl on tl.TalentID = t.TalentID
inner join Language l on l.LanguageID = tl.LanguageID
where t.TalentID = 10000;
Im in my C# application I'm using Linq to sql classes. How might I do the above code with linq to sql. Thanks.
Here's one way you can do it:
Start by creating a "results" object, something that will hold the information that you need in one object. Let's call it "TalentLanguagesContainer"
public class TalentLanguagesContainer
{
public int TalentID { get; set; }
public string FirstName { get; set; }
public int LanguageID { get; set; }
public string LanguageName { get; set; }
}
Then, create a Select statement that will map your needs appropriately:
public IQueryable < TalentLanguagesContainer > GetTalentLanguages()
{
MyDataContext _dataContext = new MyDataContext();
return _dataContext.TalentLanguages
.Where(t => t.TalentID == 10000)
.Select(tl => new TalentLanguagesContainer() {
TalentID = tl.TalentID,
FirstName = tl.Talent.FirstName,
LanguageID = tl.LanguageID,
LanguageName = tl.Language.Name });
}
Also, you may want to consider writing stored procedures for more complex scripts such as this one - you may find an SQL script to perform faster too.
Remus, I think I'm gonna answer this myself because it's such a clean solution. Check this out...
var languages = from tl in talentDB.TalentLanguages
where tl.TalentID == id
select new { lang = tl.Language.Name, tal_id = tl.TalentID }; // could get more values if needed..
foreach (var l in languages)
{
string language = l.lang;
string talentID = l.tal_id;
// etc...
}
This is pretty cool! Linq did the join for me!!