Telerik grid foreign key - c#

I have two tables, one is tblKunde and the other is tblHistorie.
They look like this:
TblKunde:
You can see the KdNr is the primary key of it.
TblHistorie:
You can see that Id is the primary key and KdNr is a foreign key which points to to the KdNr of table tblKunde.
Now my goal is to display the table TblHistorie as a KendoUI grid with columns Datum, Aktion and instead of a column KdNr it should display the Name of tblKund.
So basically it is very simple. The grid should not display the KdNr cell instad the Name of the foreignkey table.
This is a snippet of my table which are displaying columns Datum and Aktion:
.Columns(columns =>
{
columns.Bound(c => c.Id).Hidden();
columns.Bound(c => c.KdNr); // this should be the Name
columns.Bound(c => c.Datum);
columns.Bound(c => c.Aktion);
})
This is just a snippet and I marked where the name should be displayed instead of KdNr. Can someone say me how to do this?

Here is the solution for displaying values of s foreign table which is hooked up by a foreign key:
These are the tables to illustrate it better:
KdNr is the foreign key in this case
In our grid we want to display the Name from tblKunde
Our grid is bound to tblHistorie so we have to use a foreign key do display the name of tblKunde
Firstly you need to query through the foreign table like this. This is done inside the controller:
public ActionResult ToDo()
{
// Connection to database table
KundeContext KundenContext = new KundeContext();
// Select all properties from table. Especially the foreign key!!
ViewData["Kunde"] = KundenContext.Kundes.Select(e => new { KdNr = e.KdNr, Name = e.Name, Vorname = e.Vorname, Berater = e.Berater }).ToList();
return View();
}
You have to select all properties you want form the foreign table as well as the foreign key. In my case this is KdNr.
Now that you have selected all properties, put it inside your ViewBag or ViewData so that you can use it later inside the view.
Inside the grid:
columns.ForeignKey(p => p.KdNr, (System.Collections.IEnumerable)ViewData["Kunde"], "KdNr", "Name").Title("Name");
Bind to the foreign key as you would to a normal column (p => p.KdNr). It is important that you do this via columns.ForeignKey. The next step is to use IEnumerable to query through your list and bind it to your ViewData. Behind it put your foreign key in quotes (KdNr in my case) and then the column of the foreign table which you want it to bind (Name in my case). This has to be in the ViewData from the first step!!

Related

Sorting Table with Foreign Key Columns

I have a Table(Geraete) in the View which also displays data from a Foreign Table by using the public Virtual Key Ort(Foreignkey to Table Orte) to access the other Table. This works fine, but my Problem is when i want to sort the Column of foreign Values the following Code snippet does not work:
//test.Sortcolumn(String Value of the Column name which should be sorted)
var pi = typeof(Geraete).GetProperty("test.SortColumn");
//movie.Typens is from Type List Geraete
movie.Typens = (from t in movie.Typens select t).OrderBy(x => pi.GetValue(x, null)).ToList();
And yes this Snippet works for Columns of the same Entity Type Geraete.
In the View the values of the foreign Tables are easily accessable by using Ort.Columnname but this does also not work with the Code snippet above.
If you want to traverse the navigation property it would be something like
x =>
{
var o = x.GetType().GetProperty("test",x);
var pi o.GetType().GetProperty("SortColumn");
retrun pi.GetValue("SortColumn",o);
}

LINQ DeleteOnSubmit without Primary key

I have the following code and I want to delete all rows from TABLE where the column 'id' IS NOT Primary Key.
#{
using (var db = new DataClassesDataContext())
{
var query = db.Table.Where(r => r.id == 2).ToList();
if (query != null)
{
foreach (var q in query)
{
db.Table.DeleteOnSubmit(q);
}
}
db.SubmitChanges();
}}
This throws a System.InvalidOperationException because the table has not Primary Key column.
How is it possible to do that without adding a primary key in the SQL Server database?
Thanks in advance
Open the LINQ Designer. Open the properties window for the table you want to delete a record from. Click on any of the columns in the entity you want to delete and you'll see a property labeled "Primary Key". Change the value to true for column you want to use as a primary key.
P/S:This will not set the primary key on your real table.

Why is the unique constraint missing when filling the datatable?

I have the following table in SQL server
projects
id(PK, int, not null)
name (varchar(255), not null)
public_key_token (varchar(50), null)
I have added a unique constraint to the name column using
ALTER TABLE dbo.projects
ADD CONSTRAINT name_unique UNIQUE (name);
which results in a Unique, Non-Clustered index on the table (trusting SSMS).
In the code I'm retrieving the table data using
using (SqlDataAdapter adapter = new SqlDataAdapter("select * from " + DbTabName, con))
{
using (DataTable table = new DataTable(DbTabName))
{
DataTable dt = adapter.FillSchema(table, SchemaType.Source);
PkColumns = dt.PrimaryKey.Select(c => c.ColumnName).ToList();
AutoIncrementColumns = dt.PrimaryKey.Where(c => c.AutoIncrement).Select(c => c.ColumnName).ToList();
UniqueColumns = dt.Columns.Cast<DataColumn>().Where(c => c.Unique).Select(c => c.ColumnName).ToList();
...
}
}
The PKs and AutoIncrement columns are OK but in UniqueColumns I only get the PK column again.
The name column arrives in C# without the Unique constraint.
Changing the SchemaType to Mapped did not alter the result.
Why do I lose this constraint on the way to C#? Am I missing something on the SQL Server side or in C#?
[UPDATE]
#Tim-Schmelter's answer only solves the problem half way.
Just adding the index did not work. Also adding the index when the PK on the id column exists doesn't work.
The only way I got it to work was delete the table, recreate it without any key and indexes and then add the unique index as in Tim's answer. However, after adding the PK for the id column once more I'm back to the old behaviour that only the id is listed as unique column.
This is really weird.
Use this to create a unique index or use the the gui of SSMS.
CREATE UNIQUE NONCLUSTERED INDEX [name_unique] ON [dbo].[projects]
(
name ASC
)
You have added a unique constraint not a unique index.
Your code now successfully retrieves the UniqueColumns(the single column name).

on delete remove values with foreign key

I have two tables with foreign key relationship (1 to many). How can I do that when I'll remove item from first table, it will delete automatically all values with it's foreign key from second table?
So when I'll remove item from 1 table it will remove all items from 2 table whih NameId = ID of 1 table
Depends on the database management system; with MS SQL Server, you can set a foreign key to "ON DELETE CASCADE" which does exactly what you're asking for.
http://www.techonthenet.com/sql_server/foreign_keys/foreign_delete.php
You could just write a function for that:
public void RemoveWithRelatedEntries(int table1ItemID)
{
using(var db = new dbEntities())
{
// get all entities of table 2
var tab2Entities = db.table2.Where(tab2Ent=>tab2Ent.table1Reference == table1ItemID);
// remove all those entities
foreach(table2Item item in tab2Entities)
{
db.table2.Remove(item);
}
// finally remove entity from table 1
var table1entitiy = db.table1.Find(table1ItemID);
db.table1.Remove(table1entity);
db.Save();
}
}
there are probably more elegant solutions but this was what came first to my mind.

How can I insert in database values from dropdown list based on a relationship between 2 tables? I am using ASP.NET c# Entity framework, Code first

I am not talking about the id of the element in the list, but the id of it from a table if the value is in another table. E.g I have a FullName and an ID in one table and I have the same ID and some other stuff in another table(one to zero or one relationship). I have bound the FullName to a dropdown list control,but when saving,I need to refer to it's ID from the table, not the string value.
If you place something in a drop down list, you can place the ID in the value field and something else as a text, for example :
ddlCategorie.DataTextField = "Texte";
ddlCategorie.DataValueField = "ID_GLOBAL";
ddlCategorie.DataSource = db.GLOBAL.Where(t => t.DATE_FIN > dt).OrderByDescending(t => t.ID_GLOBAL).ToList();
ddlCategorie.DataBind();
As you see, I already placed the reel database value "ID" of the object inside the value field of the drop down list. So I can immediately retrieve is ID by doing :
int i = Convert.ToInt32(ddlCategorie.SelectedValue);

Categories