How to solve one to many relation tables foreign key field empty? - entity

I write this code but table relations one to many.So Person is add tables.But PersonFamily tables relations.The table is a table associated with the PersonFamily table.The code in this case works. But when I add into the PersonFamily table with ToList, the PersonFamily table data is multiplying.
Person family is taking data from two database.I want that personfamily come without data.(PersonFamily come empty.)
How can I set the StudentFamily table to come from the beginning?
How to make a clear personFamily table?
var listPerson = new List<PERSON>();
using (var t = DbContext.SingleInstance().Entities)
{
listPerson.AddRange(t.PERSON);
}
using(var personInformation=DbContext.SingleInstance().TKEntities)
{
foreach(var p in listPerson)
{
personInformation.PERSON.Add(p);
}
personInformation.SaveChanges();
}
PERSON TABLE : PersonID,NAME,SURNAME,PERSONFAMILYID,PERSONCOURSEID
PERSONFAMILY TABLE:PersonID,PERSONFAMILYID,PERSONFAMILYNAME,PERSONFAMILYSURNAME
PERSONCOURSE TABLE: PERSONID,COURSEID,COURSENAME
PERSONTABLE-PERSONFAMILY IS ONE TO MANY
PERSONTABLE-PERSONCOURSE IS ONE TO MANY.
I want to get PersonFamily table is empty.

Related

Update Table Column From Another Table?

So I have two tables. Say one table has a list of students, a student ID for each student, and a home address for each student.
Then you have another table that has a subset of the students in the first able, (and they are in a completely different order) with updated addresses and a student ID.
I need a query that can match the student ID of the two tables, and thereby update the address from the first table, using what is in the second table.
This is the query I tried, but no luck:
UPDATE Roster, UpdatedRoster
SET Roster.Address = (SELECT Address FROM UpdatedRoster WHERE Roster.StudentID = UpdatedRoster.StudentiD)
WHERE Roster.StudentID = UpdatedRoster.StudentiD
Any help here would be greatly appreciated.
Update: This is on Microsoft Access FWIW.
UPDATE Roster
SET Roster.Address = UpdatedRoster.Address
FROM Roster, UpdatedRoster
WHERE Roster.StudentID = UpdatedRoster.StudentiD

Inserting Into and Maintaining Many-to-Many Tables

SQLite3 user.
I have read thru numerous books on relational DBs and SQL and not one shows how to maintain the linking tables for many-to-many relationships. I just went through a book that went into the details of SELECT and JOINS with examples, but then glosses over the same when many-to-many relationships are covered. The author just showed some pseudo code for a table, no data, and then a pseudo code query--WTF? I am probably missing something, but it has become quite maddening.
Anyways, say I have a table like [People] with 3 columns: pID (primary), name and age. A table [Groups] with 3 columns: gID (primary), groupname and years. Since people can belong to multiple groups and groups can have multiple people, I set up a linking table called [peoplegroups] with two columns: pID, and gID both of which come from their respective tables.
So ,how do I efficiently get data into the linking table when INSERTING on the others and how do I get data out using the linking table?
Example: I want to INSERT "Jane" into [people] and make her a member of group gID 2, "bowlers" and update the linking table {peoplegroups] at the same time.
Later I want to go back and pull out a list of all of the bowlers or all the groups a person is part of.
If you already don't use primary and foreign keys (which you should!) I think you may need to consider using triggers in your design as well? So if you have a specific set of rules (e.g. if you want to create Jane with id = 1 and choose existing group 2, then after insert jane into people automatically create an entry pair personid=1,groupid=2 in the table peoplegroups. You can also create views with specific selects to see the data you want, for example if you want a query where you only show the peoples names and groups names you could create a view 'PeopleView':
SELECT P.PersonName, G.GroupName
FROM People P
INNER JOIN PeopleGroup PG ON P.PersonID = PG.PersonID
INNER JOIN Group G ON G.GroupId = PG.GroupID
then you can query 'PeopleView' saying
SELECT * FROM PeopleView WHERE GroupName = 'bowlers'
When inserting new data into the tables mentioned, the "linking" table that you are referring to needs to contain both primary keys from the other tables as foreign keys. So basically The [People] tables (pID) and the [Groups] table (gID) should both be foreign keys in the [PeopleGroups] table. In order to create a new "link" in [PeopleGroups] the record has to already exist in the [People] table as well as the [Groups] table BEFORE you try and create the link in the [PeopleGroups] table. I hope this helps

Delete from two tables with inner join

How can I delete rows from two different tables in one single query?
Part of the query is: WHERE Lendings.Id = (the id I want to delete)
The Column "ProductId" refer to the "Id" column in the Products table.
Table: Lendings
Id - ProductId
Table: Products
Id - Name
EDIT:
I do this instead :)
function DeleteLending($lendingid, $productid)
{
global $conn;
$sql = "DELETE FROM Lendings WHERE Id = ?; DELETE FROM Products WHERE Id = ?;";
$params = array($lendingid, $productid);
$stmt = sqlsrv_query($conn, $sql, $params);
}
You can't.
DELETE only deletes from one table at a time. You can, however, use the join clauses to delete in one table, depending on data in another table, but you cannot delete from two tables in one statement.
Issue two delete statements.

How to build custom PLINQO query by multiple id's?

Here's my table structure
Places
PlaceId PK
Name
...
PlaceCategories
CatId PK
Name
...
PlaceCats
PlaceId PK
CatId PK
Here's my query that pulls Places based on category id (table join)
public static IQueryable<Places> ByPlaceCat(this Table<Places> table, Expression<Func<PlaceCats, bool>> predicate) {
var db = (DataContext)table.Context;
var innerBizBase = db.PlaceCats.Where(predicate);
return db.Places.Join(innerBizBase, a => a.PlaceId, ab => ab.PlaceId, (a, ab) => a);
}
I use it like this:
places = Db.Places.ByPlaceCat(a => a.CatId == 5);
But I want to be able to pull based on a List<int> of category id's. Looking through the generated PLINQO code, a query that pulls by multiple PlaceId's (but not using a joined table) looks like this:
public static IQueryable<Places> ByPlaceId(this IQueryable<Places> queryable, IEnumerable<long> values)
{
return queryable.Where(p => values.Contains(p.PlaceId));
}
How could I essentially merge those two queries, to let me pass in a List<int> of CatId's to query by? This LINQ/PLINQO query is melting my brain. Thanks in advance!
You would need to write a extension method like this:
public static IQueryable<Places> ByPlaceCats(this Table<Places> table, IEnumerable<int> catIds)
{
var db = (TestDataContext)table.Context;
var places = (from placeCat in db.PlaceCats
join place in db.Places on placeCat.PlaceId equals place.PlaceId
where catIds.Contains(placeCat.CatId)
select place);
return places;
}
Please note that the PlaceCats table could be made into a ManyToMany relationship by adding two foreign keys to the proper tables. Once this change has been made than PLINQO will automatically generate the correct code and will create a link between the two tables skipping the intermediary table. So you could get a collection of PlaceCategories associated to the current Places entity by accessing a property on the Places entity.
Please remember to contact us if you have any questions and be sure to check out the community forums located here and PLINQO forums here.
Thanks
-Blake Niemyjski (CodeSmith Support)

Many to many with Multiple primary keys?

Situation:
TableParent with 2 primaryKeys, ParentKey1 and ParentKey2
TableChild with 1 primaryKey, ChildKey
TableConnector with columns ParentKey1, ParentKey2 and ChildKey
This is where I think I should go with my Linq query. Notice I'm fetching all childs belonging to a parent so I have it's keys as parameters.
var query = from conn in db.TableConnector
join child in db.TableChild on conn.ChildKey equals child.childKey
join par in db.TableParent on conn.ParentKey1 equals par.parentkey1 into connGroup
from co in connGroup
where co.ParentKey1 == Parameter1
Select child;
Well I tthink this works up to a point, let's say if parent had only one key, am I right?
I guess I have to join some more into a second group but I'm currently lost.
Firstly, you don't have two primary keys on your table. You can only have one primary key (hence the name primary). It sounds like you have a composite primary key, which means a key that is composed of more than one column.
I'm not sure what problem you are trying to solve, but it seems to be retrieving all TableChild rows for a given TableParent key. It should be something like this:
db.TableParent
.Single(parent => parent.ParentKey1 == key1 && parent.ParentKey2 == key2)
.TableConnectors.Select(connector => connector.TableChild)
If you have your tables mapped correctly on your Linq-to-Sql designer then you don't have to manually join them - that's what the Linq-to-Sql code generation does for you.
For example, when you have a TableConnector you will be able to retrieve the TableChild rows for it using something like this
TableConnector t = db.TableConnectors.First();
List<TableChilds> tableChilds = tableConnector.TableChilds.ToList();
tableParent only needs one primary key (it's own Id) and tableChild needs one (it's Id)
the connectorTable only needs two columns to make the many-to-many-relation work:
ParentId and ChildId
For each relation between a parent and a child you simply add one row to the connectorTable, and in order to retrieve the results try this:
select * from tableParent
inner join connectorTable
on tableParent.Id = connectorTable.ParentId
inner join tableChild
on connectorTable.ChildId = tableChild.Id
If your reason for multiple keys in the parent table is that you want to create relations between parents as well this needs to be addressed either via a relation field in the parent table (one-to-many) or another relationTable (many-to-many)