Showing EntityRef column as result - c#

I am new to LINQ to SQL and I am getting a weird result with my testing program that I don't want.
The program is a very simple WinForms app that shows SQL results in a DataGridView.
Here is my database setup.
Here is the specific column information per table.
And finally here are the results of the table shown through MSMS
Here is the issue that i'm having.
After establishing the connection to the database, I then run the following.
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
It returns this.
I have also tried this code
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.ORDERs
select Orders;
//select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
However the results are the same.
Then only way I can get the results i'm looking for is by doing this
testingDatabase = new DataClasses1DataContext(SharedVariables.TestingConnection);
var query = from Orders in testingDatabase.GetTable<ORDER>()
//select Orders;
select new { Orders.CUST_ID, Orders.ORDER_NUM, Orders.ORDER_DATE };
return query;
Then I finally get this.
Can anyone tell me how to do a "select customers" and have it not show the column displaying "LINQ_Testing.CUSTOMER". I suspect it's because it's the foreign key causing that since it makes an EntityRef variable in the CUSTOMER class.

Try adding a virtual object of Customer class in Order class:
public virtual Customer customer { get; set; }
The foreign key relation in Order class (i.e cust_id) will lazy load the Customer object in it automatically.

Related

LinqtoSQL Getting a value from another table

First time using LinqtoSQL. So to give you guys a bit of context:
I have a simple SQL Server table called Inventory with the following fields
InventoryID (int)(autoincrementing)
InventoryItemName (varchar)(255)
InventoryCategory (int)
Next I have another table called InventoryCategories for with the following fields:
InventoryCategoryID (int)(autoincrementing)
InventoryCategoryName (varchar)(255)
InventoryCategoryDescription (varchar)(255)
Next, Currently I have a combo box which selects which query to update the DataGrid.ItemSource, The code fo for this is below
if (searchcategory == "All Stock")
{
InventoryDataContext dc = new InventoryDataContext();
var q =
from a in dc.GetTable<Inventory>()
select a;
SearchResults.ItemsSource = q;
}
Now this result returns the Full table of Inventory with the columns of InventoryID, InventoryItemName, and InventoryCategory. However it returns the ID Number of InventoryCategory, in the InventoryCategory Column.
Would anyone be able to help me get the InventoryCategoryName from InventoryCategories Table in this query instead of the ID? What would be required for this?
try using left join:
var qry = from inv in context.Inventory
from invCategory in context.InventoryCategories.Where(u => inv.InventoryCategory == u.InventoryCategoryID).DefaultIfEmpty()
select new myViewModel {id = invCategory.InventoryCategoryID, categoryName = invCategory .InventoryCategoryName }
and don't forget to create myViewModel class with id and categoryName properties

Pulling data from one SQL Azure table, add a column, then populate a different table

I using C# and LINQ to pull/push data housed in SQL Azure. The basic scenario is we have a Customer table that contains all customers (PK = CompanyID) and supporting tables like LaborTypes and Materials (FK CompanyID to Customer table).
When a new customer signs up, a new record is created in the Customers table. Once that is complete, I want to load a set of default materials and laborTypes from a separate table. It is simple enough if I just wanted to copy data direct from one table to another but in order to populate the existing tables for the new customer, I need to take the seed data (e.g. laborType, laborDescription), add the CompanyID for each row of seed data, then do the insert to the existing table.
What the best method to accomplish this using C# and LINQ with SQL Azure?
An example of a direct insert from user input for LaborTypes is below for contextual reference.
using (var context = GetContext(memCustomer))
{
var u = GetUserByUsername(context, memUser);
var l = (from lbr in context.LaborTypes
where lbr.LaborType1.ToLower() == laborType
&& lbr.Company == u.Company
select lbr).FirstOrDefault();
if (l == null)
{
l = new AccountDB.LaborType();
l.Company = u.Company;
l.Description = laborDescription;
l.LaborType1 = laborType;
l.FlatRate = flatRate;
l.HourlyRate = hourlyRate;
context.LaborTypes.InsertOnSubmit(l);
context.SubmitChanges();
}
result = true;
}
What you'll want to do is write a query retrieving data from table B and do an Insert Statement on Table A using the result(s).
This has been covered elsewhere in SO I think, here would be a good place to start
I don't know the syntax for Linq specifically; but by constructing something similar to #Murph 's answer beyond that link, I think this might work.
var fromB= from b in TableB
where ... ;//identify the row/data from table B
// you may need to make fromB populate from the DB here.
var toInsert = ...; //construct your object with the desired data
// do other necessary things here
TableA.InsertAllOnSubmit(toInsert);
dc.SubmitChanges(); // Submit your changes

Simple Sql query conversion to Linq To Sql

I tried to convert this simple sql query to linq to sql query
SELECT * INTO temptable from EFESRDP0
ALTER TABLE temptable DROP COLUMN PASSWORD,SECONDPASS
SELECT * FROM temptable
DROP TABLE temptable
But I couldnt. Anyhelp would be appreciated, thank you.
Since Linq to SQL has no equivalent for the table operations you're trying to perform, the short answer is you can't do that.
From the structure of the query though it looks like the following is happening:
All records from EFESRDP0 are added to a previously non-existent table temptable
A few columns are dropped from temptable
The remaining data is returned as a recordset
The temporary table is dropped
Which is a long-winded way of specifying a list of columns to return from the original table, isn't it? Bad SQL shouldn't be turned into even worse LINQ, it should be fixed.
In query syntax the simple form would be:
var results =
from row in context.EFESRDP0
select new { row.ID, row.Name, row.LastLoginTime /* or whatever */ };
This will result in an SQL query similar to:
SELECT ID, Name, LastLoginTime
FROM EFESRDP0;
Which is a whole lot simpler than the SQL you posted and appears to do basically the same thing without all the table gymnastics.
Since your SQL statements are effectively returning all columns except Password and SECONDPASS, you can do that with a simple Linq like Corey gave creating a new anonymous type. You can also have a type defined with all the columns except those 2 so you could get a typed result. ie: This sample returns only 3 columns from sample Northwind..Customers table:
void Main()
{
DataContext db = new DataContext(#"server=.\SQLexpress;trusted_connection=yes;database=Northwind");
Table<Customer> Customers = db.GetTable<Customer>();
// for LinqPad
//Customers.Dump();
}
[Table(Name = "Customers")]
public class Customer
{
[Column]
public string CustomerID { get; set; }
[Column]
public string ContactName { get; set; }
[Column]
public string CompanyName { get; set; }
}

Get value from source after adding linq to sql Select

I would like to bind a dropdownlist with a product name and an orderItemID as its value (both from two separate tables but with relations)
Heres the database design (some columns left out for brevity)
Order - ID, Name, address
OrderItems - ID, OrderID, ProductID, Price
Products - ID, Name, description, Price
Heres the code to connect it all
var oList = ReturnOrderItems(OID).Select(pr => new {pr.Product.Name }).ToList();
DropdownListItems.DataSource = oList;
DropdownListItems.DataTextField = "NEED THE ORDER ITEM ID";
DropdownListItems.DataValueField = "Name";
DropdownListItems.DataBind();
ReturnOrderItems is a simple method to get all order items by order ID.
Then i added a Select to return the product name (as OrderItems has a relationship to the products table).
So far this works and returns the product name which is fine but how could i get the ID of the order item (which would be held inside the ReturnOrderItems(OID) method?
I've tried several ways but the most i get is productID which is no good - how should i be doing this?
Assuming that the method returns a collection ofOrderItem then you would do
var oList = ReturnOrderItems(OID).Select(pr => new {pr.Product.Name, pr.ID }).ToList();
Also are you sure you want to store the name and display the id, otherwise i think you want this:
DropdownListItems.DataTextField = "Name";
DropdownListItems.DataValueField = "ID";

C# Comparing values from 2 tables in SQL Server Database 2005 and displaying in Gridview in VS2005

I am using VS2005 C# and SQL Server Database 2005.
I am tying to compare values between 2 databases.
I am able to retrieve the variable [StudentName] from tStudent Table via a SELECT WHERE sql statement, as follow:
Now, I have another table named StudentDetails. It has 3 columns, StudentName,Address and ContactNum:
The situation is that I want to grep the result from the first SQL query on tStudent, which returns me a list of Students whose [Status]=DELETED.
And from the list of Students queried , I want to take one Student at a time, and search through my [StudentDetails] table.
If it exist in [StudentDetails], I wan to use a way to store the variable [StudentName] from StudentDetails table and display it in GridView on my webpage.
(open to many solutions here. store in database; display result in GridView; store in array; etc)
May I know what the ways and steps I can take to achieve the result?
Step by step guide and code snippets are very much appreciated, because I am quite weak in C# programming.
you can do like this:
Use Visual Studio to create a DataSet name StudentDS, create table name "Student" in this DataSet, this table will contain 3 table columns: String StudentName; String Address; String ContactNum;
Fill deleted students into this DataSet:
DataSet dset = new StudentDS();
String connectionString = "";// depends on your database system, refer to http://www.connectionstrings.com
using (connection = new OdbcConnection(connectionString))
{
connection.Open();
command.Connection = connection;
command.CommandText = "select StudentName, Address, ContactNum from tStudent WHERE status = 'DELETE'";
OdbcDataAdapter da = new OdbcDataAdapter();
da.SelectCommand = command;
da.Fill(dset, "Student");
}
- After you get this DataSet, you can iterate on its row to do what you want.
if(dset.Tables[0].Rows != null) {
for (int i = 0; i < dset.Tables[0].Rows.Count, i++){
if(!ExistInStudentDetail(dset.Tables[0].Rows[i]["StudentName"]))
{
dset.Tables[0].Rows.remove(i);
i--;
}
}
}
//here, boolean ExistInStudentDetail(String StudentName) is a method, you can create sql for this as same in above.
In your form, add a new DataGridView name "StudentForm",add 1 column for this DataGridView name "StudentName", and set its binding property to "StudentName" (same column name in DataSet), and then set DataSource of this grid.
StudentForm.DataSource = dSet;
HTH.
This is a fairly simple issues but the scope is pretty large. So here goes:
First you should really make sure you have unique columns in the tables you are searching this allows you to modify those individual rows and make sure that you are modifying the correct one. I didn't see any ID columns in the screenshot so I just wanted to cover this.
Second I would create a class for students. In here I would create fields or properties of all the information that I wanted.
class Student
{
public string Name { get; private set; }
public string Address { get; private set; }
public string ContactNum { get; private set; }
}
you can either use a constructor in the above class and fill the properties with that or you can fill in each through your select your choice.
Third I would create a List<Student> students; this will be used as your reference list
List<Student> deletedStudents = SQL Select Statement;
Fourth I would then create another List<Student> detailedStudents;
Finally I would compare the two lists and then do something when a match is found.

Categories

Resources