.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Easy Web
Imran Ghani
Post New Web Links

a problem with Linq to Entities

Posted By:      Posted Date: September 30, 2010    Points: 0   Category :ASP.Net
 

hi

i have a query that get some data from database and i want to databind a drop down list control that have alredy an item in it

the code is:

Private Sub DatabindFamilyMembers()

        Dim db As New AghakhanianEntities()
        Dim members = From m In db.UserProfiles _
                     Where m.IsFamilyMember = True _
                     Select FullName = m.FirstName + m.MiddleName + m.LastName, m.ProfileID _
                     Order By FullName

        Dim i As Integer = 0
        Dim text As String
        Dim value As String
        Do While i <= members.Count()
            value = members(i).ProfileID
            text = CType(members(i).FullName, String)
            i = i + 1
            ddlParent.Items.Insert(i, New ListItem(text, value))

        Loop

        ddlParent.DataBind()
    End Sub


when i run it in line value=.... get some error like:

LINQ to Entities does not recognize the method 'VB$AnonymousType_2`2[System.String,System.Int32] ElementAtOrDefault[VB$AnonymousType_2`2](System.Linq.IQueryable`1[VB$AnonymousType_2`2[System.String,System.Int32]], Int32)' method, and this method cannot be translated into a store expression.


View Complete Post


More Related Resource Links

LINQ query with multiple joins, problem

  

I am using a LINQ query with multiple joins, the last join does not return any values even though values exist in the database. Below is my code.

when the query returns suiteNameTrg and SuiteTypeTrg are empty, all other values are returned correctly.

string suiteNameTrg = string.Empty;
            string suiteTypeTrg = string.Empty;
            using (DataClassesDataContext db = new DataClassesDataContext())
            {  
                    var productQuery = from assets in db.ASSETs
                    join relocatableUnits in db.RELOCATABLE_UNITs on assets.RUID equals relocatableUnits.RUID into assets_units
                    from relocatableUnits in assets_units.DefaultIfEmpty()
                   join build in db.BUILDINGs on assets.BUILDING_ID equals build.BUILDING_ID into assets_bins
                   from build in assets_bins.DefaultIfEmpty()
                   join test in db.TEST_SUITEs on assets.TEST_SUITE_ID equals test.TEST_SUITE_ID into test_bins
                   from test in test_bins.DefaultIfEmpty()
                    
                    join testTrgt in db.TEST_SUITEs on assets.TARGET_TEST_SUITE_ID equals testTrgt.TEST_SUITE_ID into testTrgt_bins
                    from testTrgt in testTrgt_bins.DefaultIfEmpty()

                    select new
                                   {
                          

Serializing Linq to Entities for use in a REST Service

  
What would be the best approach to send data retrieved from Linq to Entities over a rest service? For example, if you have a Linq to Entities class, say Products from the Northwind database. I want to return a subset of the Products (based on a query on the model) back through a service. First a retrieve a List<Product> from the context, and then i need to serialize the data and send it over the wire. If I use the exact Linq to Entities class, then there is so much "garbage" that it either fails outright (from a circular reference) or you are wasting bandwith. What is a design to overcome this? Create POCO objects for each linq to entities class you want to send and create custom code to tranform each object in the list to the POCO object? This is the only way I can see doing it, although it would be very tedius to create and maintain (unless some custom code generation was created). Is there a better approach? clients

Problem updating records with LINQ, Concurrency?

  
 My project includes a grid view with some updtable fields, some fields throw an error on update and some do not and it does not really make sense. WORK_STATION_ID does not cause an error, ROOM _ID cause an error, both are int? (I am using c#) and for update I use the code liste below.using (DataClassesDataContext db = new DataClassesDataContext()) { var product = (from p in db.ASSETs where p.ASSET_ID == ASSET_ID select p).Single(); product.WORK_STATION_ID=WORK_STATION_ID; product.ROOM_ID=ROOM_ID; db.SubmitChanges(); }    Row not found or changed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.Linq.ChangeConflictException: Row not found or changed. Source Error: Line 93: Line 94: Line 95: db.SubmitChanges(); Line 96: Line 97: Source File: C:\Projects\TEST_II\trunk\ObjectDataSourceLibrary\AssetController.cs Line: 95 Stack Trace: [ChangeConflictException: Row not found or changed.] System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +963417 Syst

Problem while retrieving data from a lookup column from sharepoint linq.

  
Hi I am working with sharepoint linq concept. When I am giving a query with lookup column It's working fine.  But when i am trying to retrieve the data from a look up column to spgridview. I was unable to get the output. Here is the above code which i have worked.   string strTitle = string.Empty; string strStatus=string.Empty; var context = new LinqSampleDataContext(SPContext.Current.Web.Url); EntityList<SharePoint2010ConceptsItem> Concept = context.GetList<SharePoint2010ConceptsItem>("SharePoint 2010 Concepts"); var query = from cs in Concept where cs.Status.Title.ToString()!="Completed" select new { cs.Title, cs.Id, //cs.Status }; sgvConcepts.DataSource =query; sgvConcepts.DataBind();   Any help me plz how to retrieve the data from a lockup column.bvnprasad

Problem with Retrieving data from lookup column using SharePoint 2010 Linq Concept

  
Hi I am working with sharepoint linq concept. When I am giving a query with lookup column It's working fine.  But when i am trying to retrieve the data from a look up column to spgridview. I was unable to get the output. Here is the above code which i have worked.   string strTitle = string.Empty; string strStatus=string.Empty; var context = new LinqSampleDataContext(SPContext.Current.Web.Url); EntityList<SharePoint2010ConceptsItem> Concept = context.GetList<SharePoint2010ConceptsItem>("SharePoint 2010 Concepts"); var query = from cs in Concept where cs.Status.Title.ToString()!="Completed" select new { cs.Title, cs.Id, //cs.Status }; sgvConcepts.DataSource =query; sgvConcepts.DataBind();   Any help me plz how to retrieve the data from a lockup column.bvnprasad

Change connection string of Linq to Sql entities

  
Hi all.I have a solution which uses Linq to SQL Data Classes to acced the db. I have a project for my domain objects in my solution, which is a class library and has the dbml file. When I set up the dmbl using the wizard, Visual Studio created an app.config file on that project with the connection string. It also creatting a settings file with the same info. I've noticed that if I change the connection string in the settings file, the app.config gets updated, which is the expected behaviour.However, I'm having a problem when I deploy my web site to the production server. I already set the app.config file's Build Action to "Content", and also set Copy to ouput directory to "Always". Nevertheless, when I install the web site and change the connection string in the app.config file, it still takes the old connection string, so obviously I get an error. I've found that it only works if I change it with in Visual Studio and then compile, but of course that's not an optimal solution, because any change in the production db server would mean I have to change my project's assembly, thus generating a new version.Any thing I'm missing? What do I have to configure so that the assembly takes the connection string form my app.config file directly after I deploy?Thanks a lot.

Left Outer Join in LINQ + Entities

  
HiI have found quite a bit of info on the net, but I can't get it to work. Here's the normal SQL query:SELECT cl.ID AS ClientID, cl.Name, cl.Surname, CLC1.PHONECODE + ' ' + CLC1.PHONENUMBER AS WorkNum, CLC2.PHONECODE + ' ' + CLC2.PHONENUMBER AS HomeNum, CLC3.PHONECODE + ' ' + CLC3.PHONENUMBER AS CellNum, CLC1.PREFERRED AS WorkNumPref, CLC2.PREFERRED AS HomeNumPref, CLC3.PREFERRED AS CellNumPref, veh.ID AS VehicleID, veh.MAKE, veh.MODEL, veh.YEAR, veh.REGNO, ws.ID AS WorkshopID, ws.JOBTYPE, ws.SERVICEADVISOR, ws.TIMEFINISHED, ws.TECHNICIAN, fs.ID as FollowupID, fs.TYPE, fs.DESCRIPTION, fs.SCHEDULEDATE, fs.WRONGNUMBERFLAG FROM CLIENTS AS cl LEFT OUTER JOIN CLIENTCONTACTNUMBERS AS CLC1 ON cl.ID = CLC1.CLIENTID AND CLC1.TYPE = 'W' LEFT OUTER JOIN CLIENTCONTACTNUMBERS AS CLC2 ON cl.ID = CLC2.CLIENTID AND CLC2.TYPE = 'H' LEFT OUTER JOIN CLIENTCONTACTNUMBERS AS CLC3 ON cl.ID = CLC3.CLIENTID AND CLC3.TYPE = 'C' INNER JOIN CLIENTVEHICLES AS clveh ON cl.ID = clveh.CLIENTID INNER JOIN VEHICLES AS veh ON clveh.VEHICLEID = veh.ID INNER JOIN WSBOOKINGS AS ws ON clveh.ID = ws.CLIENTVEHICLEID INNER JOIN FOLLOWUPSCHEDULE AS fs ON fs.WSBOOKINGID = ws.ID WHERE fs.ID = 2 There is a multiple join between CLIENTS and CLIENTCONTACTNUMBERS so it would return a single row of data. If you were to do a normal join on CLIENTS and C

Linq to SQL Web Service cannot be serialized problem

  
Hello All, Ok so I'm playing around with Web Services using Linq to SQl. I apparently have  a lot of learning to do. What I'm trying to do below is pull data from the Northwind db Employee Table. I don't need to see the whole table, I'm just trying to select individual(s) but I keep getting the following error  "System.Data.Linq.Binary cannot be serialized because it does not have a parameterless constructor" Code Below: Thanks in advance for any advice <WebMethod()> _ Public Function EmployeeInfo() As List(Of Employee) Dim db As New NorthwindDataContext() Dim output = From cust In db.Employees _ Select cust.EmployeeID, cust.FirstName, cust.LastName Return output End Function  

Linq to SQL - Association Property Name problem

  
Is it possible to specifiy a custom property name for a foreign key association in Linq to Sql? For example, if you have an "Order" class that has a "Customer" EntityRef, that's fine.  But what if instead of myOrder.Customer you wanted the property name to be myOrder.PreferredCustomer.sqlmetal and the designer are both always using the table name as the Property name.  So myOrder.Customer is the only option I have, other than hacking through the generated file.You can change the storage option of the association attribute, but that pertains to the underlying member, NOT the public property.Thanks.

LINQ: Problem in fetching data

  
Hi, i am developing something in LINQ, in this i am using some query for selecting data like this:var data = (from w in db2.TextSubCats where w.SubCatName.Trim()==reci_i.Recipe_cat.Trim() select w.SubCatName);but how could i fetch this data, i knows there is a solution by using foreach statement like this:foreach (var data_i in data){}my problem is this, if there no data returned by query then this foreach statment is just skipped.....so how could i get data returned by query in string so that i could perform my string manipulations... Thanks for your time.

Custom Webpart not working on "My Profile" page but works on all other pages. Linq Problem?

  
Hi, I created a publication site and in that site i created pages with specifique metadata (using a pagelayout with a custom content type)0. My webpart is getting data from those pages and displaying it. My webpart works on every page except on the "my profile" page(overview tab). I get the following error: Invalid Url: /TestSites/course I used the SPMETAL to create a class and i'm using this class to retrieve the data from the pages (with linq). The url i give to the entity is http://pcp/TestSites/course  this works fine on every site except on the my profile page. Can anybody help me? Here is the code i use to retrieve my data: EntitiesDataContext ctx = new EntitiesDataContext(courseSite); //Code below gets only the pages with a courses contentType. //EXCEPTION TRIGGERT ON THE FOLLOWING LINE IF IN PROFILE PAGE EntityList<Courses> course = ctx.GetList<Courses>("Pages"); //Writing the query to get the correct pages(with the course page layout only! var Query = from myCourse in course.ToList() where myCourse.CourseParticipants.Contains(myWeb.CurrentUser.LoginName) Select new{myTitle = myCourse.CourseTitle, myCompany = myCourse.Company, myPath = myCourse.Path, myName = myCourse.Name }; Thx.    

How to use SP with Linq to Entities?

  

Hi!

How to use Stored Procedures with Linq to Entities?
I prefer an example with input and output

The videos on asp.net only show how to do this with Linq to SQL.

Thank you!


Linq to entities: Always select before delete and update?

  

Hi,

With linq to entities, how can I delete and update data inside a database without first selecting the complete entity at first?
The idea behind this is to improve performance.

Thanks!


Linq to Entities Many to Many Persistence Issue

  

I am having problems persisting a many to many. My code saves the Problem but not the users that can be attached to a problem. My Linq to Entities Mapping is below in the first three code blocks. I then have my ASP MVC controller method which receives a problem, a file (optional), and a string array of users which are allowed to view the problem. I retrieve the Users from the UserRepository and add them to a List which is then passed through to the ProblemRespository with the problem and added to the problem.Users collection. However when submitted only the problem is being saved and not the records which are required in the junction table. Any help would be appreciated. This is the first time I've attempted my own mapping.
Thanks in advance.

Problem with SQL server 2008 UDF and model data entities

  

Hi everyone. I'm very new with this technology and still have to learn lot's of stuff...

I managed to start with basic MVC design but i'm now stuck on adding functions to model..


I created view in mssql

CREATE VIEW MyFirstView
AS
SELECT table1.Field1, table2.Field2
FROM table1 INNER JOIN table2 ON table1.Field1 = table2.Field1


and function


CREATE FUNCTION fnGetMyViewResult(@paramField nvarchar)
RETURNS TABLE
AS
RETURN SELECT * FROM MyFirstView WHERE MyFirsView.Field1 = @paramField





but when i run entity data model wizzard from VS 2010 i can chose only from tables, views and stored procedures. There is no way (atleast no way i know about) to add my sql function to MVC model...

I can see function in ServerExplorer but not in wizzard....

Can someone help me with this?


Thanks in advance..



Problem with adding custom propety to a data class using Linq.

  

Hello,

I tried to add a custom property to the data model:


public partial class Department
    {
        public string ExtensionIdName
        {
            get
            {
                return Extension.ExtensionName;
            }
            set
            {
            }
        }
    }

It seems that it works, but when I bind the data to a ListView it shows all the properties except the property I added manualy (ExtensionIdName).

Am I missing something or is there something wrong?


Dynamic LINQ Where problem

  

Guys

I am using LINQ TO ENTITIES.

I stumbled upon a problem while using Dynamic LINQ which is provided by Scott Guthrie. Basically I need a functionality where the user would be able to search by anything while on a gridview. Now the issue is that when the field to be searched is a string it works without problems, when it is an interger it is giving me a {"Operator '=' incompatible with operand types 'Int32?' and 'String'"}. Now the issue is that I would not be able to know what datatype the field is. If I convert the data to an INT it works without problems, but as I said I cannot since I would not be able to know beforehand the database data type. The place where it is giving me the error is shown in bold.

 

The second issue is that I have a CONTAINS functionality where the user would be able to type in anything and the system will create a CONTAINS linq statement to search for data. For one field it works without problems, while for another field the CONTAINS does not work and it gives me an OBJECT NOT SET TO AN INSTANCE when I try to access the list.  The code is shown underneath. I am using MVC and jqGrid.

private static string BuildWhereClause(JQGridRequest.SearchOperatorOptions SearchOperator, string FieldName)

{

 

swit

Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend