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


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

Linq to Entities Many to Many Persistence Issue

Posted By:      Posted Date: October 01, 2010    Points: 0   Category :ASP.Net
 

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.

View Complete Post


More Related Resource Links

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

WF Service using EF4 POCO Entities Issue

  
Hi I've a WF Service using my EDMX and my Classes generated using a poco t4 template, but on execution when i include navigation properties related to a 1 to many or many to many relationships i got an underlying connection was closed error. I've traced the error and i got 2 exceptions different exceptions depending on which parameters i pass to my context and my ReciveAndSendReply Action. One is the related to that Navigation Property and the fact that it is generating a cyclic reference A.B  B.List<A> or viceversa and cant be serialized. The other changing my context property to enabling/disabling the proxy creation i get a overflow on the max message size or max message on the trace (the cyclic reference is doing an overflow and the entity back from the WF service is not coming back. Hope you can help me guys to figure out whats going on. Thx Pedro

Compile issue with List<> and Linq

  
I am pretty sure this is some framework version issue but I am getting this on a (custom layout) page compile migrated over from MOSS. The following code complies in my MOSS 2007 environment but does not in my new 2010 environment. Thanks in advance for any help. Code section #1: private bool isSuccessReturnCode(string s) { bool bReturn = false; // Following line fails looking for ';' XDocument loaded = XDocument.Parse(s); var q = from c in loaded.Descendants("Node") select (string)c.Element("ReturnCode");   Code Section #2 private InvoiceItem getInvoiceItem(Guid ID) { List<InvoiceItem> InvoiceItems = ((List<InvoiceItem>)ViewState["INVOICEITEMS"]);

Linq forward compatibility issue

  
In Linq 3.5 I used to be able to do this, but the code in bold is no longer compatible in Linq 4.0, Is there another way to declare the query variable prior to assigning it (PLEASE DO NOT SUGGEST TO DECLARE AS VAR, IT DOES NOT WORK AND CAN NOT BE DECLARED AS NULL):   ProjectArtifactsDataContext dbProjectAttributes = new ProjectArtifactsDataContext();IQueryable<ProjectArtifacts.Defect> query1 = null;   This type of declaration allowed me to create aggregate and complex queries such as         if (UserControlHost.ShowMyItemsOnly)        {            Guid currentUserId = (Guid)Membership.GetUser(Membership.GetUser().UserName).ProviderUserKey;            query1 = dbProjectAttributes.Defects.Where(defect =>                 defect.Active == true && defect.AssignedTo == currentUserId);        }         else        {            if (FilterInactive == true)                que

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 Compact db, file copy issue

  
Our application uses LINQ and SQL compact database .sdf file as datasource.  It is using Miscrosoft SQL Server Compact 3.5 SP 1 and .NET Framework 3.5 SP1. We store our application's project data into a .sdf file.  When our application opens a .sdf file (e.g. projectA.sdf), it will make a temporary copy of it and open the temporary file instead of the original file.  If we change one table cell value (i.e. one property value of an object that is created by LINQ), and call DataContext.SubmitChanges(ConflictMode.ContinueOnConflict), and then call File.Copy(DataContext.Connection.Database, filename, true); to copy the temporary file back to the original file (replacing the original one).   We found that the table value is not changed in projectA.sdf.  But in the temporary copy, the value is changed.  If we re-open db connection by calling DataContext.Connection.Close(); DataContext.Connection.Open(); right before calling File.Copy(), the changed value is copied successfully to projectA.sdf. If we do a lot of value changes in the database, or adding / deleting table row, then submit changes.  Without re-opening the db connection, after File.Copy(), the projectA.sdf have those changes copied. This strange behaviour looks like the temporary db file is cached.  For a small change, the cached version is not changed.  The File.Copy() use t

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 SQL Classes (dbml file) across multiple websites issue

  

Hello

I have a single LINQ to SQL Classes (dbml file) compiled in a Class Library that's referenced by 3 websites. Inside that Class Library there's also a class that's using the DBML to manipulate data.

At one point it needs to save in a user table the user info (firstname, lastname, email). SOMEHOW (!?) two of the 3 webapps saves email instead of firstname and viceversa while the other 1 saves them correctly ! The one compiled last seems to be the one saving correctly.

There's no code error as I have debugged this multiple times. The values are assigned correctly but before the SubmitChanges() call the data inside the database object is corrupted.

Now, I have already fixed this locally by putting every website in a separate AppPool (which also needs to be set to "Classic" and not "Integrated". However I really don't want to bug the client with such IIS changes so I'm looking for another workaround !

Please Help!

Regards

Mihai



a problem with Linq to Entities

  

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.

Linq Float/Double Issue

  

I'm using linq to sql, and everything seems to be working fine except one thing, I'm showing any mapped float fields from my db tables as "Double?" instead of "Double", and when binding to a datagrid, any of those "Double?" fields don't show.


If I iterate through the items and spit out the property, the float value is indeed there and properly returned.  What's going on here?


Object Must Implement IConvertible error in LINQ to Entities with group by

  
1 down vote favorite
1

Hi. I have an ASP.NET MVC application in which i am using entity model for connecting to MySQl database

Here I am joining 2 tables and then applying group by on one of the fields. Then fetching the result from GroupBy result. Everything is working fine on development machine but getting  error:

"Object Must Implement IConvertible"   when executing on the stagging server.

Can you please help me out why such error is occurring. I have taken the dump of database form staging server and then used that on development machine then also working fine. But when I placed the dump of development machine database on staging then getting the same exception.

So where is problem i am not understanding.

The model structure is

student:
studentid
int
course
string
name
string

student_payment
:
id
int
studentid
int
amount
decimal

Here student and st

How can I get two tables in only one query with LINQ to Entities?

  

Code for example:

var context = new cEntities();

var query = from m in context.Users where m.UserId==2

select m from c in context.Folder where c.FolderId==5 select c;

 


I don't want to write var query twice and connect twice to DB, I want to do it one var query only.


Is this possible at all? Getting to different tables at once?


No connection between the tables, but I want to save DB connection.

 


 

 

 


Any opinions on using Projection or explicit join syntax when joining entities in Linq to SQL?

  

Folks,

I would like to know whether people use the join syntax OR projection when joining entities in LINQ to SQL queries. I have noticed that when using projection that a CROSS JOIN is in the generated SQL

e.g. 

var query =
from o in Orders
from  oi in o.OrderItems
where oi.OrderId == o.OrderId

generates SQL something like...

FROM [Customer].[Orders] AS [t0]
CROSS JOIN [Customer].[OrderItems] AS [t1]
WHERE ([t1].[OrderId] = [t0].[OrderId]) AND ([t1].[OrderId] = [t0].[OrderId])

whereas with explicit joins I get a clean inner join..

var query =
from o in Orders
join oi in OrderItems on o.OrderId equals oi.OrderId

generates..

FROM [Customer].[Orders] AS [t0]
INNER JOIN [Customer].[OrderItems] AS [t1] ON [t0].[OrderId] = [t1].[OrderId] 

I know using explicit joins over projection is frowned upon, but I am wary of those cross joins.

Just wondering what other folks preferences are when using joins in L2SQL.

Cheers

K

 

 


Custom database function cannot be translated into a LINQ to Entities store expression

  

Hi,

I'm trying to get a UDF from my SQL Server database to map to Linq to Entities. I've found an example for the CourseManager sample in the MSDN :

Private

 

 

Sub Button1_Click(

LINQ To SharePoint - SPMetal Issue

  

Hi All,

We an issue with LINQ to SharePoint in creating entities class. Whenever i created the entities class using SPMetal, one or more columns are automatically created in RemoveColumnAttribute something as shown below.

    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
    [Microsoft.SharePoint.Linq.RemovedColumnAttribute()]
    public override string Status
    {
      get
      {
        throw new System.InvalidOperationException("Field WorkflowPRStatus was removed from content type.");
      }
      set
      {
        throw new System.InvalidOperationException("Field WorkflowPRStatus was removed from content type ");
      }
    }

Could anyone faced this issue and how to get rid of this Remove

ColumnAttribute?

Any suggestions are welcome.

Thanks

Chandrasekaran C N


Chandrasekaran C N
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