Search Results

Search found 9232 results on 370 pages for 'linq tutorial'.

Page 11/370 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • LINQ and conversion operators

    - by vik20000in
    LINQ has a habit of returning things as IEnumerable. But we have all been working with so many other format of lists like array ilist, dictionary etc that most of the time after having the result set we want to get them converted to one of our known format. For this reason LINQ has come up with helper method which can convert the result set in the desired format. Below is an example var sortedDoubles =         from d in doubles         orderby d descending         select d;     var doublesArray = sortedDoubles.ToArray(); This way we can also transfer the data to IList and Dictionary objects. Let’s say we have an array of Objects. The array contains all different types of data like double, int, null, string etc and we want only one type of data back then also we can use the helper function ofType. Below is an example     object[] numbers = { null, 1.0, "two", 3, "four", 5, "six", 7.0 };     var doubles = numbers.OfType<double>(); Vikram

    Read the article

  • LINQ and Aggregate function

    - by vik20000in
    LINQ also provides with itself important aggregate function. Aggregate function are function that are applied over a sequence like and return only one value like Average, count, sum, Maximum etc…Below are some of the Aggregate functions provided with LINQ and example of their implementation. Count     int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };     int uniqueFactors = primeFactorsOf300.Distinct().Count();The below example provided count for only odd number.     int[] primeFactorsOf300 = { 2, 2, 3, 5, 5 };     int uniqueFactors = primeFactorsOf300.Distinct().Count(n => n%2 = 1);  Sum     int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };        double numSum = numbers.Sum();  Minimum      int minNum = numbers.Min(); Maximum      int maxNum = numbers.Max();Average      double averageNum = numbers.Average();  Aggregate      double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };     double product = doubles.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);  Vikram

    Read the article

  • LINQ: Single vs. SingleOrDefault

    - by Paulo Morgado
    Like all other LINQ API methods that extract a scalar value from a sequence, Single has a companion SingleOrDefault. The documentation of SingleOrDefault states that it returns a single, specific element of a sequence of values, or a default value if no such element is found, although, in my opinion, it should state that it returns a single, specific element of a sequence of values, or a default value if no such element is found. Nevertheless, what this method does is return the default value of the source type if the sequence is empty or, like Single, throws an exception if the sequence has more than one element. I received several comments to my last post saying that SingleOrDefault could be used to avoid an exception. Well, it only “solves” half of the “problem”. If the sequence has more than one element, an exception will be thrown anyway. In the end, it all comes down to semantics and intent. If it is expected that the sequence may have none or one element, than SingleOrDefault should be used. If it’s not expect that the sequence is empty and the sequence is empty, than it’s an exceptional situation and an exception should be thrown right there. And, in that case, why not use Single instead? In my opinion, when a failure occurs, it’s best to fail fast and early than slow and late. Other methods in the LINQ API that use the same companion pattern are: ElementAt/ElementAtOrDefault, First/FirstOrDefault and Last/LastOrDefault.

    Read the article

  • Hex Dump using LINQ (in 7 lines of code)

    - by Fabrice Marguerie
    Eric White has posted an interesting LINQ query on his blog that shows how to create a Hex Dump in something like 7 lines of code.Of course, this is not production grade code, but it's another good example that demonstrates the expressiveness of LINQ.Here is the code:byte[] ba = File.ReadAllBytes("test.xml");int bytesPerLine = 16;string hexDump = ba.Select((c, i) => new { Char = c, Chunk = i / bytesPerLine })    .GroupBy(c => c.Chunk)    .Select(g => g.Select(c => String.Format("{0:X2} ", c.Char))        .Aggregate((s, i) => s + i))    .Select((s, i) => String.Format("{0:d6}: {1}", i * bytesPerLine, s))    .Aggregate("", (s, i) => s + i + Environment.NewLine);Console.WriteLine(hexDump); Here is a sample output:000000: FF FE 3C 00 3F 00 78 00 6D 00 6C 00 20 00 76 00000016: 65 00 72 00 73 00 69 00 6F 00 6E 00 3D 00 22 00000032: 31 00 2E 00 30 00 22 00 20 00 65 00 6E 00 63 00000048: 6F 00 64 00 69 00 6E 00 67 00 3D 00 22 00 75 00000064: 3E 00Eric White reports that he typically notices that declarative code is only 20% as long as imperative code. Cross-posted from http://linqinaction.net

    Read the article

  • C# SQL Statement transformed TO LINQ how can i translate this statement to a working linq

    - by BlackTea
    I am having trouble with this I have 3 Data tables i use over and over again which are cached I would like to write a LINQ statement which would do the following is this possible? T-SQL VERSION: SELECT P.[CID],P.[AID] ,B.[AID], B.[Data], B.[Status], B.[Language] FROM MY_TABLE_1 P JOIN ( SELECT A.[AID], A.[Data], A.[Status], A.[Language] FROM MY_TABLE_2 A UNION ALL SELECT B.[AID], B.[Data], B.[Status], B.[Language] FROM MY_TABLE_3 B ) B on P.[AID] = B.[AID] WHERE B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1 AND B.[Language] = 'EN' OR B.[Language] = 'ANY' AND B.STATUS = 1 Then i would like it to create a result set of the following Results: |CID|AID|DATA|STATUS|LANGUAGE

    Read the article

  • How to parse deeply nested using LINQ to XML

    - by Picflight
    How do I parse the following XML using LINQ? I need to insert into a database table OrderNumber, ShipAddress, ShipCity, ShipState for each Order & OrderCancelled. Then in a separate table I need to insert OrderId from the Returns/Amount section. <!-- language: lang-xml --> <?xml version="1.0" encoding="utf-8"?> <OrdersReport Date="2012-08-01"> <Client> <ClientId>1</ClientId> <Orders> <Order> <OrderNumber>1</OrderNumber> <ShipAddress>123 Main St.</ShipAddress> <ShipCity>MyCity</ShipCity> <ShipState>AZ</ShipState> </Order> <Order> <OrderNumber>2</OrderNumber> <ShipAddress>111 Main St.</ShipAddress> <ShipCity>OtherCity</ShipCity> <ShipState>AL</ShipState> </Order> <OrderCancelled> <OrderNumber>3</OrderNumber> <ShipAddress>111 Main St.</ShipAddress> <ShipCity>OtherCity</ShipCity> <ShipState>AL</ShipState> </OrderCancelled> </Orders> <Returns> <Amount> <OrderId>2</OrderId> <OrderId>3</OrderId> </Amount> </Returns> </Client> <Client> <ClientId>2</ClientId> <!-- Same Tree structure as Client 1 --> </Client> </OrdersReport> Not sure why the XML is not showing red and blue colors and not indenting properly. :-(

    Read the article

  • LINQ Query Returning Multiple Copies Of First Result

    - by Mike G
    I'm trying to figure out why a simple query in LINQ is returning odd results. I have a view defined in the database. It basically brings together several other tables and does some data munging. It really isn't anything special except for the fact that it deals with a large data set and can be a bit slow. I want to query this view based on a long. Two sample queries below show different queries to this view. var la = Runtime.OmsEntityContext.Positions.Where(p => p.AccountNumber == 12345678).ToList(); var deDa = Runtime.OmsEntityContext.Positions.Where(p => p.AccountNumber == 12345678).Select(p => new { p.AccountNumber, p.SecurityNumber, p.CUSIP }).ToList(); The first one should hand back a List. The second one will be a list of anonymous objects. When I do these queries in entities framework the first one will hand me back a list of results where they're all exactly the same. The second query will hand me back data where the account number is the one that I queried and the other values differ. This seems to do this on a per account number basis, ie if I were to query for one account number or another all the Position objects for one account would have the same value (the first one in the list of Positions for that account) and the second account would have a set of Position objects that all had the same value (again, the first one in it's list of Position objects). I can write SQL that is in effect the same as either of the two EF queries. They both come back with results (say four) that show the correct data, one account number with different securities numbers. Why does this happen??? Is there something that I could be doing wrong so that if I had four results for the first query above that the first record's data also appears in the 2-4th's objects??? I cannot fathom what would/could be causing this. I've searched Google for all kinds of keywords and haven't seen anyone with this issue. We partial class out the Positions class for added functionality (smart object) and some smart properties. There are even some constructors that provide some view model type support. None of this is invoked in the request (I'm 99% sure of this). However, we do this same pattern all over the app. The only thing I can think of is that the mapping in the EDMX is screwy. Is there a way that this would happen if the "primary keys" in the EDMX were not in fact unique given the way the view is constructed? I'm thinking that the dev who imported this model into the EDMX let the designer auto select what would be unique. Any help would give a haggered dev some hope!

    Read the article

  • Unable to add item to dataset in Linq to SQL

    - by Mike B
    I am having an issue adding an item to my dataset in Linq to SQL. I am using the exact same method in other tables with no problem. I suspect I know the problem but cannot find an answer (I also suspect all i really need is the right search term for Google). Please keep in mind this is a learning project (Although it is in use in a business) I have posted my code and datacontext below. What I am doing is: Create a view model (Relevant bits are shown) and a simple wpf window that allows editing of 3 properties that are bound to the category object. Category is from the datacontext. Edit works fine but add does not. If I check GetChangeSet() just before the db.submitChanges() call there are no adds, edits or deletes. I suspect an issue with the fact that a Category added without a Subcategory would be an orphan but I cannot seem to find the solution. Command code to open window: CategoryViewModel vm = new CategoryViewModel(); AddEditCategoryWindow window = new AddEditCategoryWindow(vm); window.ShowDialog(); ViewModel relevant stuff: public class CategoryViewModel : ViewModelBase { public Category category { get; set; } // Constructor used to Edit a Category public CategoryViewModel(Int16 categoryID) { db = new OITaskManagerDataContext(); category = QueryCategory(categoryID); } // Constructor used to Add a Category public CategoryViewModel() { db = new OITaskManagerDataContext(); category = new Category(); } } The code for saving changes: // Don't close window unless all controls are validated if (!vm.IsValid(this)) return; var changes = vm.db.GetChangeSet(); // DEBUG try { vm.db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException) { vm.db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges); vm.db.SubmitChanges(); } The Xaml (Edited fror brevity): <TextBox Text="{Binding category.CatName, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding category.CatDescription, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" /> <CheckBox IsChecked="{Binding category.CatIsInactive, Mode=TwoWay}" /> IssCategory in the Issues table is the old, text based category. This field is no longer used and will be removed from the database as soon as this is working and pushed live.

    Read the article

  • Linq to XML query returining a list of strings

    - by objectsbinding
    Hi all, I have the following class public class CountrySpecificPIIEntity { public string Country { get; set; } public string CreditCardType { get; set; } public String Language { get; set; } public List<String> PIIData { get; set; } } I have the following XML that I want to query using Linq-to-xml and shape in to the class above <?xml version="1.0" encoding="utf-8" ?> <piisettings> <piifilter country="DE" creditcardype="37" language="ALL" > <filters> <filter>FIRSTNAME</filter> <filter>SURNAME</filter> <filter>STREET</filter> <filter>ADDITIONALADDRESSINFO</filter> <filter>ZIP</filter> <filter>CITY</filter> <filter>STATE</filter> <filter>EMAIL</filter> </filters> </piifilter> <piifilter country="DE" creditcardype="37" Language="en" > <filters> <filter>EMAIL</filter> </filters> </piifilter> </piisettings> I'm using the following query but I'm having trouble with the last attribute i.e. PIIList. var query = from pii in xmlDoc.Descendants("piifilter") select new CountrySpecificPIIEntity { Country = pii.Attribut("country").Value, CreditCardType = pii.Attribute("creditcardype").Value, Language = pii.Attribute("Language").Value, PIIList = (List<string>)pii.Elements("filters") }; foreach (var entity in query) { Debug.Write(entity.Country); Debug.Write(entity.CreditCardType); Debug.Write(entity.Language); Debug.Write(entity.PIIList); } How Can I get the query to return a List to be hydrated in to the PIIList property.

    Read the article

  • Getting a linq table to be dynamically sent to a method

    - by Damian Spaulding
    I have a procedure: var Edit = (from R in Linq.Products where R.ID == RecordID select R).Single(); That I would like to make "Linq.Products" Dynamic. Something like: protected void Page_Load(object sender, EventArgs e) { something(Linq.Products); } public void something(Object MyObject) { System.Data.Linq.Table<Product> Dynamic = (System.Data.Linq.Table<Product>)MyObject; var Edit = (from R in Dynamic where R.ID == RecordID select R).Single(); My problem is that I my "something" method will not be able to know what table has been sent to it. so the static line: System.Data.Linq.Table Dynamic = (System.Data.Linq.Table)MyObject; Would have to reflect somthing like: System.Data.Linq.Table Dynamic = (System.Data.Linq.Table)MyObject; With being a dynamic catch all variable so that Linq can just execute the code just like I hand coded it statically. I have been pulling my hair out with this one. Please help.

    Read the article

  • Working with Joins in LINQ

    - by vik20000in
    While working with data most of the time we have to work with relation between different lists of data. Many a times we want to fetch data from both the list at once. This requires us to make different kind of joins between the lists of data. LINQ support different kinds of join Inner Join     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupJoin =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country         select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName }; Group Join – where By the joined dataset is also grouped.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var custSupQuery =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         select new { Key = sup.Country, Items = cs }; We can also work with the Left outer join in LINQ like this.     List<Customer> customers = GetCustomerList();     List<Supplier> suppliers = GetSupplierList();      var supplierCusts =         from sup in suppliers         join cust in customers on sup.Country equals cust.Country into cs         from c in cs.DefaultIfEmpty()  // DefaultIfEmpty preserves left-hand elements that have no matches on the right side         orderby sup.SupplierName         select new { Country = sup.Country, CompanyName = c == null ? "(No customers)" : c.CompanyName,                      SupplierName = sup.SupplierName};Vikram

    Read the article

  • Using Dynamic LINQ to get a filter for my Web API

    - by Espo
    We are considering using the Dynamic.CS linq-sample included in the "Samples" directory of visual studio 2008 for our WebAPI project to allow clients to query our data. The interface would be something like this (In addition to the normal GET-methods): public HttpResponseMessage List(string filter = null); The plan is to use the dynamic library to parse the "filter"-variable and then execute the query agains the DB. Any thoughts if this is a good idea? Is it a security problem?

    Read the article

  • "Enumeration yielded no results" When using Query Syntax in C#

    - by Shantanu Gupta
    I have created this query to fetch some result from database. Here is my table structure. What exaclty is happening. DtMapGuestDepartment as Table 1 DtDepartment as Table 2 Are being used var dept_list= from map in DtMapGuestDepartment.AsEnumerable() where map.Field<Nullable<long>>("GUEST_ID") == DRowGuestPI.Field<Nullable<long>>("PK_GUEST_ID") join dept in DtDepartment.AsEnumerable() on map.Field<Nullable<long>>("DEPARTMENT_ID") equals dept.Field<Nullable<long>>("DEPARTMENT_ID") select dept.Field<string>("DEPARTMENT_ID"); I am performing this query on DataTables and expect it to return me a datatable. Here I want to select distinct department from Table 1 as well which will be my next quest. Please answer to that also if possible.

    Read the article

  • How to create Query syntax for multiple DataTable for implementing IN operator of Sql Server

    - by Shantanu Gupta
    I have fetched 3-4 tables by executing my stored procedure. Now they resides on my dataset. I have to maintain this dataset for multiple forms and I am not doing any DML operation on this dataset. Now this dataset contains 4 tables out of which i have to fetch some records to display data. Data stored in tables are in form of one to many relationship. i.e. In case of transactions. N records per record. Then these N records are further mapped to M records of 3rd table. Table 1 MAP_ID GUEST_ID DEPARTMENT_ID PARENT_ID PREFERENCE_ID -------------------- -------------------- -------------------- -------------------- -------------------- 19 61 1 1 5 14 61 1 5 15 15 61 2 4 10 18 61 2 13 23 17 61 2 20 26 16 61 40 40 41 20 62 1 5 14 21 62 1 5 15 22 62 1 6 16 24 62 2 3 4 23 62 2 4 9 27 62 2 13 23 25 62 2 20 24 26 62 2 20 25 28 63 1 1 5 29 63 1 1 8 34 63 1 5 15 30 63 2 4 10 33 63 2 4 11 31 63 2 13 23 32 63 40 40 41 35 65 1 NULL 1 36 65 1 NULL 1 38 68 2 13 22 37 68 2 20 25 39 68 2 23 27 40 92 1 NULL 1 Table 2 Department_ID Department_Name Parent_Id Parent_Name -------------------- ----------------------- --------------- ---------------------------------------------------------------------------------- 1 Food 1, 5, 6 Food, North Indian, South Indian 2 Lodging 3, 4, 13, 20, 23 Room, Floor, Non Air Conditioned, With Balcony, Without Balcony 40 New 40 SubNew TABLE 3 Parent_Id Parent_Name Preference_ID Preference_Name -------------------- ----------------------------------------------- ----------------------- ------------------- NULL NULL NULL NULL 1 Food 5, 8 North Indian, Italian 3 Room 4 Floor 4 Floor 9, 10, 11 First, Second, Third 5 North Indian 14, 15 X, Y 6 South Indian 16 Dosa 13 Non Air Conditioned 22, 23 With Balcony, Without Balcony 20 With Balcony 24, 25, 26 Mountain View, Ocean View, Garden View 23 Without Balcony 27 Mountain View 40 New 41 SubNew I have these 3 tables that are related in some fashion like this. Table 1 will be the master for these 2 tables i.e. table 2 and table 3. I need to query on them as SELECT Department_Id, Department_Name, Parent_Name FROM Table2 WHERE Department_Id in ( SELECT Department_Id FROM Table1 WHERE guest_id=65 ) SELECT Parent_Id, Parent_Name, Preference_Name FROM Table3 WHERE PARENT_ID in ( SELECT parent_id FROM Table1 WHERE guest_id=65 ) Now I need to use these queries on DataTables. So I am using Query Syntax for this and reached up to this point. var dept_list= from dept in DtMapGuestDepartment.AsEnumerable() where dept.Field<long>("PK_GUEST_ID")==long.Parse(63) select dept; This should give me the list of all departments that has guest id =63 Now I want to select all departments_name and parent_name from Table 2 where guest_id=63 i.e. departments that i fetched above. This same case will be followed for Table3. Please suggest how to do this. Thanks for keeping up patience for reading my question.

    Read the article

  • When using Query Syntax in C# "Enumeration yielded no results". How to retrieve output

    - by Shantanu Gupta
    I have created this query to fetch some result from database. Here is my table structure. What exaclty is happening. DtMapGuestDepartment as Table 1 DtDepartment as Table 2 Are being used var dept_list= from map in DtMapGuestDepartment.AsEnumerable() where map.Field<Nullable<long>>("GUEST_ID") == DRowGuestPI.Field<Nullable<long>>("PK_GUEST_ID") join dept in DtDepartment.AsEnumerable() on map.Field<Nullable<long>>("DEPARTMENT_ID") equals dept.Field<Nullable<long>>("DEPARTMENT_ID") select dept.Field<string>("DEPARTMENT_ID"); I am performing this query on DataTables and expect it to return me a datatable. Here I want to select distinct department from Table 1 as well which will be my next quest. Please answer to that also if possible.

    Read the article

  • LINQ and ordering of the result set

    - by vik20000in
    After filtering and retrieving the records most of the time (if not always) we have to sort the record in certain order. The sort order is very important for displaying records or major calculations. In LINQ for sorting data the order keyword is used. With the help of the order keyword we can decide on the ordering of the result set that is retrieved after the query.  Below is an simple example of the order keyword in LINQ.     string[] words = { "cherry", "apple", "blueberry" };     var sortedWords =         from word in words         orderby word         select word; Here we are ordering the data retrieved based on the string ordering. If required the order can also be made on any of the property of the individual like the length of the string.     var sortedWords =         from word in words         orderby word.Length         select word; You can also make the order descending or ascending by adding the keyword after the parameter.     var sortedWords =         from word in words         orderby word descending         select word; But the best part of the order clause is that instead of just passing a field you can also pass the order clause an instance of any class that implements IComparer interface. The IComparer interface holds a method Compare that Has to be implemented. In that method we can write any logic whatsoever for the comparision. In the below example we are making a string comparison by ignoring the case. string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "cHeRry"}; var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());  public class CaseInsensitiveComparer : IComparer<string> {     public int Compare(string x, string y)     {         return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);     } }  But while sorting the data many a times we want to provide more than one sort so that data is sorted based on more than one condition. This can be achieved by proving the next order followed by a comma.     var sortedWords =         from word in words         orderby word , word.length         select word; We can also use the reverse() method to reverse the full order of the result set.     var sortedWords =         from word in words         select word.Reverse();                                 Vikram

    Read the article

  • Linq To Sql and identity_insert

    - by Ronnie Overby
    I am trying to do record inserts on a table where the primary key is an Identity field. I have tried calling mycontext.ExecuteCommand("SET identity_insert myTable ON") but this doesn't do any good. I get an error saying that identity_insert is off when I submit changes. How can I turn it ON from the c# code before I submit changes? EDIT I have read that this is because ExecuteCommand's code gets executed in a different session. EDIT 2 Is there any way I can execute some DDL to remove the Identity Specification from my C# code, do the inserts, and then turn Identity Specification back on?

    Read the article

  • Linq-to-SQL: Ignore null parameters from WHERE clause

    - by Peter Bridger
    The query below should return records that either have a matching Id supplied in ownerGroupIds or that match ownerUserId. However is ownerUserId is null, I want this part of the query to be ignored. public static int NumberUnderReview(int? ownerUserId, List<int> ownerGroupIds) { return ( from c in db.Contacts where c.Active == true && c.LastReviewedOn <= DateTime.Now.AddDays(-365) && ( // Owned by user !ownerUserId.HasValue || c.OwnerUserId.Value == ownerUserId.Value ) && ( // Owned by group ownerGroupIds.Count == 0 || ownerGroupIds.Contains( c.OwnerGroupId.Value ) ) select c ).Count(); } However when a null is passed in for ownerUserId then I get the following error: Nullable object must have a value. I get a tingling I may have to use a lambda expression in this instance?

    Read the article

  • C#: Fill DataGridView From Anonymous Linq Query

    - by mdvaldosta
    // From my form BindingSource bs = new BindingSource(); private void fillStudentGrid() { bs.DataSource = Admin.GetStudents(); dgViewStudents.DataSource = bs; } // From the Admin class public static List<Student> GetStudents() { DojoDBDataContext conn = new DojoDBDataContext(); var query = (from s in conn.Students select new Student { ID = s.ID, FirstName = s.FirstName, LastName = s.LastName, Belt = s.Belt }).ToList(); return query; } I'm trying to fill a datagridview control in Winforms, and I only want a few of the values. The code compiles, but throws a runtime error: Explicit construction of entity type 'DojoManagement.Student' in query is not allowed. Is there a way to get it working in this manner?

    Read the article

  • linq select m:n user:groups

    - by cduke
    Hi guys, I've got three tables: cp_user (id, name) cp_group (id, name) cp_usergroup (user_id, group_id) the classical m:n stuff. Assume the following Data: cp_user 1, Paul 2, Steven cp_group 1, Admin 2, Editor cp_usergroup 1, 1 1, 2 2, 2 So Paul is in the Admin AND Editor group, while Steven is just in the Editor group. I want to generate a list like that from the database: Paul Admin Paul Editor Steven Editor Any suggestions? Thanks! Clemens

    Read the article

  • DynamicQuery: How to select a column with linq query that takes parameters

    - by Richard77
    Hello, We want to set up a directory of all the organizations working with us. They are incredibly diverse (government, embassy, private companies, and organizations depending on them ). So, I've resolved to create 2 tables. Table 1 will treat all the organizations equally, i.e. it'll collect all the basic information (name, address, phone number, etc.). Table 2 will establish the hierarchy among all the organizations. For instance, Program for illiterate adults depends on the National Institute for Social Security which depends on the Labor Ministry. In the Hierarchy table, each column represents a level. So, for the example above, (i)Labor Ministry - Level1(column1), (ii)National Institute for Social Security - Level2(column2), (iii)Program for illiterate adults - Level3(column3). To attach an organization to an hierarchy, the user needs to go level by level(i.e. column by column). So, there will be at least 3 situations: If an adequate hierarchy exists for an organization(for instance, level1: US Embassy), that organization can be added (For instance, level2: USAID).-- US Embassy/USAID, and so on. How about if one or more levels are missing? - then they need to be added How about if the hierarchy need to be modified? -- not every thing need to be modified. I do not have any choice but working by level (i.e. column by column). I does not make sense to have all the levels in one form as the user need to navigate hierarchies to find the right one to attach an organization. Let's say, I have those queries in my repository (just that you get the idea). Query1 var orgHierarchy = (from orgH in db.Hierarchy select orgH.Level1).FirstOrDefault; Query2 var orgHierarchy = (from orgH in db.Hierarchy select orgH.Level2).FirstOrDefault; Query3, Query4, etc. The above queries are the same except for the property queried (level1, level2, level3, etc.) Question: Is there a general way of writing the above queries in one? So that the user can track an hierarchy level by level to attach an organization. In other words, not knowing in advance which column to query, I still need to be able to do so depending on some conditions. For instance, an organization X depends on Y. Knowing that Y is somewhere on the 3rd level, I'll go to the 4th level, linking X to Y. I need to select (not manually) a column with only one query that takes parameters. Thanks for helping

    Read the article

  • Fill WinForms DataGridView From Anonymous Linq Query

    - by mdvaldosta
    // From my form BindingSource bs = new BindingSource(); private void fillStudentGrid() { bs.DataSource = Admin.GetStudents(); dgViewStudents.DataSource = bs; } // From the Admin class public static List<Student> GetStudents() { DojoDBDataContext conn = new DojoDBDataContext(); var query = (from s in conn.Students select new Student { ID = s.ID, FirstName = s.FirstName, LastName = s.LastName, Belt = s.Belt }).ToList(); return query; } I'm trying to fill a datagridview control in Winforms, and I only want a few of the values. The code compiles, but throws a runtime error: Explicit construction of entity type 'DojoManagement.Student' in query is not allowed. Is there a way to get it working in this manner?

    Read the article

  • Linq to Entities and POCO foreign key relations mapping (1 to 0..1) problem

    - by brainnovative
    For my ASP.NET MVC 2 application I use Entity Framework 1.0 as my data access layer (repository). But I decided I want to return POCO. For the first time I have encountered a problem when I wanted to get a list of Brands with their optional logos. Here's what I did: public IQueryable<Model.Products.Brand> GetAll() { IQueryable<Model.Products.Brand> brands = from b in EntitiesCtx.Brands.Include("Logo") select new Model.Products.Brand() { BrandId = b.BrandId, Name = b.Name, Description = b.Description, IsActive = b.IsActive, Logo = /*b.Logo != null ? */new Model.Cms.Image() { ImageId = b.Logo.ImageId, Alt = b.Logo.Alt, Url = b.Logo.Url }/* : null*/ }; return brands; } You can see in the comments what I would like to achieve. It worked fine whenever a Brand had a Logo otherwise it through an exception that you can assign null to the non-nullable type int (for Id). My workaround was to use nullable in the POCO class but that's not natural - then I have to check not only if Logo is null in my Service layer or Controllers and Views but mostly for Logo.ImageId.HasValue. It's not justified to have a non null Logo property if the id is null. Can anyone think of a better solution?

    Read the article

  • LINQ error when deployed - Security Exception - cannot create DataContext

    - by aximili
    The code below works locally, but when I deploy it to the server it gives the following error. Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file. Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. The code is protected void Page_Load(object sender, EventArgs e) { DataContext context = new DataContext(Global.ConnectionString); // <-- throws the exception //Table<Group> _kindergartensTable = context.GetTable<Group>(); Response.Write("ok"); } I have set full write permissons on all files and folders on the server. Any suggestions how to solve this problem? Thanks in advance.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >