IEnumerable implementation

I use LINQ, and it's hard for me to understand how I can make the new "domain model" classes work in LINQ when querying through tables. I am using Linq for SQL and C # in .NET 3.5.

Suppose I need 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 a row in a tClient table plus one additional column in tClientSetting.

Annoying errors I get: It is not possible to initialize the type "ExtendedClient" with the initializer of the collection, since it does not implement "System.Collections.IEnumerable", and it is also impossible to implicitly convert the type "System.Linq.IQueryable" to "ExtendedClient". Explicit conversion exists (are you skipping listing?)

I understand that this is a basic error, but I cannot determine how to BEST implement IEnumerable, because I cannot find an example.

Do I have to do this every time I need a specialized object? Thanks in advance.

+4
source share
2 answers
 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 will need to do a similar thing every time you need to return a specialized object. If you do not need to return it, you do not need to specify a type, and you do not need a special class. You can 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 }; 
+6
source

Why do you use a special type for this?

I think you can do client.Settings.strValue if you configure the Client-Settings relation to create the Client.Settings property (instead of Settings.Client ). And as far as I remember, such a configuration is possible in LINQ.

0
source

All Articles