EntityFramework: one to many relationship without foreign key - entity-framework

I've got a problem with mapping relations in existing database.
I have two tables:
table1
table1Id (primary key)
table1Code
table1Field
table2
table2Id (primary key)
table1Code
table2Field
And I've a one-to-many relation between table2 and table1. So I need in table2 object table2.table1 which will be filled by looking for table1 row in table1 by table1Code. Of course I need ICollection<table2> inside table1.
There is reference in database:
ALTER TABLE table2 WITH CHECK ADD CONSTRAINT [FK_table2_table1]
FOREIGN KEY([table1Code]) REFERENCES table1 ([table1Code])
I use EntityFramework-Reverse-POCO-Code-First-Generator which generates mapping below:
HasRequired(a => a.table1)
.WithMany(b => b.table2)
.HasForeignKey(c => c.table1Code);
And when I try to use it I see that generated SQL code compares table1Id with table1Code (I think that it's because of table1Id as foreign key usage.)
Is it possible to create such mapping between those two tables, which are connected by table1Code?

Related

How to use ON CONFLICT with a primary key on a foreign table

I am basically trying to replicate data from a table on one server to another.
I have two identical databases on the servers. I created a foreign table called opentickets_aux1 to represent the opentickets table on the secondary server on the primary server. Both have a primary key of incidentnumber. I can access the data in the foreign table just fine but when I try the following SQL,I get "ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification."
INSERT INTO opentickets_aux1 (SELECT * FROM opentickets)
ON CONFLICT (incidentnumber)
DO
UPDATE SET
status = EXCLUDED.status,
lastmodifieddate = EXCLUDED.lastmodifieddate
I want to update a few columns if the primary key exist. I use this statement for other queries and they work when its a local table. Any ideas?
A foreign table cannot have a primary key constraint, because PostgreSQL wouldn't be able to enforce its integrity. Therefore, you cannot use INSERT ... ON CONFLICT with foreign tables.
Your idea also does not handle rows that are deleted on the foreign server, but maybe that's intentional.
If you want a local copy of a foreign table, the easiest way would be to create a materialized view on the foreign table.
If that is not your desire (perhaps because you don't want to copy deletions), you'd have to use statements like
INSERT INTO localtable
SELECT * FROM foreigntable f
WHERE NOT EXISTS
(SELECT 1 FROM localtable l
WHERE f.id = l.id);
UPDATE localtable l
SET /* all columns from f */
FROM foreigntable f
WHERE f.id = l.id
AND (f.*) <> (l.*);

Cannot create foreign key constraint on table w/ inheritance

I'm trying to add a foreign key constraint to an existing table:
ALTER TABLE address
ADD FOREIGN KEY(company_id)
REFERENCES company(company_id) ON DELETE CASCADE DEFERRABLE;
That fails with:
ERROR: insert or update on table "address" violates \
foreign key constraint "address_company_id_fkey"
DETAIL: Key (company_id)=(83376) is not present in table "company".
Yet the company table does have that key:
DB=> SELECT company_id FROM company WHERE company_id = 83376;
company_id
------------
83376
(1 row)
I suspect that this is due to table inheritance (old database, very historic reasons), company is a base table and one derived table is the person table. Which is the one containing the actual key:
DB=> SELECT company_id FROM person WHERE company_id = 83376;
company_id
------------
83376
(1 row)
I'm specifically targeting the base table (assuming it contains the data of all derived tables) because the address rows refer to different derived tables.
Is there a way to make that work?
Or as an alternative, kinda even better, is there a way to have foreign keys targeting specific derived tables?

How can I join two tables by a foreign key table in Entity Framework?

I am trying to join two tables by a foreign key table in linq.
The two tables are
Items and Classes, and the foreign key table is ItemClasses (ItemId, ClassId).
My context does not have a DBSet for the foreign key table, and when I try to add it I get a model creation error.
When I saw the error, I noticed that this code referred to the foreign key table
modelBuilder.Entity<Classes>()
.HasMany(e => e.Items)
.WithMany(e => e.Classes)
.Map(m => m.ToTable("ItemClasses").MapLeftKey("ClassId").MapRightKey("ItemId"));
So it looks like I should be able to refer to the items through the class, but how do I join the tables?
I'd like to do something like this
query = from ig in myCtx.Items.AsNoTracking()
//join di in myCtx.ItemClasses.AsNoTracking() on ig.Id equals di.ClassId
join c in myCtx.Classes.AsNoTracking() on di.ClassId equals c.Id
join dd in myCtx.SalesAssociates.AsNoTracking() on dd.Id equals ig.SalesAssociateId
How do I do joins when the fk table is not in my context, but is referred to in one of the tables?
First, you have a configuration error. With HasMany / WithMany you are actually configuring the automatic "link" table, so
m.ToTable("Classes")
should be
m.ToTable("ItemClasses")
or how exactly you want that table to be named in the database.
Second, when working with EF, it's always preferred to use navigation properties rather than joins. In case of many-to-many relationship with auto link table, using navigation properties is mandatory. EF will produce the necessary joins for you.
So instead of join your would use something like this:
query = from ig in myCtx.Items.AsNoTracking()
from c in ig.Classes
...

PostgreSQL insert if foreign key exists

How can I insert a new row in a table with a foreign key reference only if the foreign key (in this case model) exists?
Currently I have the following statement:
INSERT INTO furniture (model, type) VALUES (modelA, chair)
Use a SELECT that returns nothing if the FK does not exist.
INSERT INTO furniture (model, type)
select 'modelA', 'chair'
where exists (select *
from model
where model.model = 'modelA');
You did not tell us what the referenced table is called. I assumed it's model - you need to adjust that to the real names.

It is possible :Two references to one column in PostgreSQL?

Is it possible to allow two optional foreign key?
For example:
table a (id, nameA)
table b(id nameB)
table c(id ,name)
that the name in table c is a foreign key
and it can contracts or the id from table a or the id from table b.
If its possible, what the way to create it?