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

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

How does Linq to Sql Determine which tables to write to

Posted By:      Posted Date: September 10, 2010    Points: 0   Category :ASP.Net
I was wondering how Linq to Sql determines which tables to write to when given primary/foreign Key relationships.  I can (hopefully) better explain using an example.  I have the following tables: Customer CustomerStatus CustomerType CustomerAddresses Therefore I have a Customer Entity, a CustomerStatus entity, a CustomerType Entity and a List of CustomerAddresses.  In my code, I load up the Customer Entity and the List of CustomerAddresses because that's all I need.  For some reason Linq to Sql is trying to insert a new Customer Status record.  I have no idea why its doing this.  Can anyone please explain to me how linq to sql determines which table(s) will be written to based on the entities above? Thanks

View Complete Post

More Related Resource Links

How to write the LINQ query for the following

Hello All, I have an entity type with the following properties: UnitId, UnitDescription, ParentId, EffectiveDate - (Say the entitty type is Unit)  I want to filter out a list of UnitIds whose effective date is less than a given date. But since there could be many EffectiveDate s less than a given date, I want to take the latest one(Max). Simply told, I want to get the unit ids with the most recent effective date prior to a given date. How can I do this in a single linq statement? Appriciate any help.

How to MAP Tables in Linq .dbml file

I am using VS 2010I've created LiNQ .dbml file via   .. Model>Add New Item>Data>LINQ to SQL ClasesI've put table on designer surface using drag & drop.I've done all this from one tutorial. There Is Mapping with arrows between tables in tutorial. How can i do this.. ???Can Any one Help Me Please..Thanks

Can i write stored proc for the two queries, truncating and inserting two different tables?

Hi All, I have two queries below. trying to write stored proc so i can combine these queries so i can use only one execute sql task. both the queries are truncating and inserting records in two different tables. QUERY 1 à   truncate table [PlanFinder].[InvalidAwps] go   INSERT INTO [PlanFinder].[InvalidAwps]     (Ndc, AwpUnitCost)     SELECT DISTINCT P.Ndc Ndc, A.Price AwpUnitCost     FROM         PlanFinder.PlanFinder.HpmsFormulary P         LEFT JOIN (SELECT Ndc, Price FROM MHSQL01D.Drug.FdbPricing.vNdcPrices                     WHERE PriceTypeCode = '01' AND CurrentFlag = 1) A     ON P.Ndc = A.Ndc      WHERE (A.Ndc IS NULL OR A.Price <= 0 OR A.Price IS NULL)     AND p.Ndc IS NOT NULL --------------------------------------------------------- Query 2 à   truncate table [PlanFinder].[MissingNdcs] go   INSERT INTO [PlanFinder].[MissingNdcs]     (Ndc)     SELECT DISTINCT Ndc     FROM         PlanFinder.InvalidAwps       WHERE AwpUnitCost IS NULL  Thanks a

LINQ-to-SQL: How do you join more than 2 tables?

Hi there, I was trying to find out how I can join more than 2 tables using the LINQ-to-SQL syntax. For instance, joining 2 tables in SQL:  SELECT * FROM Table1 AS T1 INNER JOIN Table2 AS T2 ON T1.Key=T2.Column1WHERE T2.Key='17'; can be expressed as: var Result = from T1 in DbContext.Table1 join T2 in DbContext.Table2 on T1.Key equals T2.ForeignKey where T2.Key=17 select new { T1, T2 }; But how would I join 3 or more tables using LINQ? For example: SELECT * FROM (Table1 AS T1 INNER JOIN Table2 AS T2 ON T1.Key=T2.Column1) INNER JOIN Table3 AS T3 ON T3.Key=T2.Column2 WHERE T2.Key='37'; I've been searching and experimenting and I cannot seem to find any informraiton on this. One example I found involves putting the result for the frist join into a temp object, and then performing the second join. I'm not sure performance-wise if that's the same as doing a 3-table join directly using a single SQL statement. Any help will be greatly appreciated! Thanks,- K.  

linq - delete two tables not work

BurnbetDataContext db = new BurnbetDataContext(); var q = (from c in db.GetTable<tbl_Payment>() where c.UserId == "fc44c835-8e80-45ee-af84-68339a09c053" select c).Single<tbl_Payment>(); db.GetTable<tbl_Payment>().DeleteOnSubmit(q); db.SubmitChanges(); In App_Code I BurnbetDataContext.I have two tables and tbl_PaymentDetails tbl_PaymentAssociation is:Parent Child Class -->>> UserId UserId ClassData in Table tbl_PaymentDetails (child) does not delete.      

Entity Framework - how to join tables without LINQ and with only string?


Hi all,

I have a question about Entity Framework. Please answer if you know answer on this. I have such query :

    String queryRaw =
        "SELECT " +
        "p.ProductName AS ProductName " +
        "FROM ProductEntities.Products AS p " +
        "INNER JOIN CategoryEntities.Categories AS c " +
        "ON p.CategoryID = c.CategoryID ";
    ObjectQuery<DbDataRecord> query = new ObjectQuery<DbDataRecord>(queryRaw, entityContext);
    GridView1.DataSource = query;

Particularly I want to join few tables in one query, but I can NOT use LINQ and can NOT use ObjectQuery with objects mapped to DB fields inside my query. Because each entity creates dynamically. So this is what i can NOT use :



The question is can I use something like this instead of using objects?

query.Join ("INNER JOIN CategoryEntities.Category ON p.CategoryID = c.CategoryID ");

How to write SQL Insert into query using LINQ


How I can write following SQL query using LINQ. There is no default constraint define for the ID column so we have explicitly pass the NEWID().

I want to replicate the products of a company to another company.

Insert Into Products
Select NEWID() AS ProductID, ProductName, CompanyID = @DestinationID, ProductCategoryID From Products Where CompanyID = @SourceID

Also once I get these result how can I use InsertAllOnSubmit to insert all the records at once without looping it.

How do I write this kind of Linq query?



I have this kind of class:

class A{
  public int a;
  public int b=0;

and I have this list: List<A> l;

for example. data in this l is: {a=1,b=0},{a=2,b=0},{a=3,b=0},{a=1,b=0},{a=3,b=0}

Now I would like to find out every A in l, that if there are more than two A that have same value of a, then their b should all be set to 1.

In this case, the list of l should finally like: {a=1,b=1},{a=2,b=0},{a=3,b=1},{a=1,b=1},{a=3,b=1}

because there are two A have value 1 of a, and two A have value 3 of a, only the second A in the list has unique value 2 of a.

Please teach me how to write this kind of linq query.


Does Linq dbml need refreshed after allowing cascade deletes on tables?


Hi all-

When setting up my database, I forgot to set the delete rule to cascade on foreign keys.  Now, I can't delete a user from the ASP.net control panel due to the FK constraints.  So, I need to go through all my tables and allow cascade delete on all keys.

Once I do this, will I need to redo  my Linq .dbml?  (ie: delete each table on it and drag it back on) or does it not matter?

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.





No data write from DB in LINQ/Repeater



Can someone tell me why i get at blank page with this code, its not making the repeater.


<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="repeater1.aspx.vb" Inherits="LinqSQL_connection.repeater1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
    <a href="default.aspx">Tilbage til liste
        </a><br />
    <asp:Repeater ID="Repeater1" runat="server">
                <asp:Label ID="lblID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "TestID")%>' />
                <asp:Label ID="lblTitle" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "TestTitle")%>' />
                <asp:Label ID="lblText" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "TestText")%>' />
        <br /><br /><br />


Playing with Linq grouping: GroupByMany?

One of its features is grouping. Many people understand grouping like it is defined in Sql. Linq is implementing grouping quite the same way. Let's discover this syntax and how to make consecutive groups easier.

LINQ : Implementing IN and NOT IN

I got tried of typing

var result = from s in source
where items.Contains(s)
select s;and so I implemented the IN and NOT IN methods as extension methods:

101 LINQ Samples Tutorials

101 LINQ Example with sample code snippets....This sample prints each element of an input integer array whose value is less than 5. The sample uses a query expression to create a new sequence of integers and then iterates over each element in the sequence, printing its value

Linq: how to share parameters between lambda expressions ?

When using Linq to objects, you will quickly feel the need to pass some parameters from a method to another but it's not so easy because each Linq method is not calling the following one. In a Linq sequence, each method is using the result computed by the previous one. So, local contexts are not visible from one method to another.
The compiler is using two technical different ways to let parameters go out of a method.

Linq to Sql CompiledQuery container

Ok now let's go. Here is just a little trick but with some interesting patterns that could be useful in some other contexts not connected to Linq to Sql.

When using Linq expressions, like with Linq to Sql, translating the expression into something else (sql for example) is taking time and resources. Sometimes it's negligible, sometimes not...
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