Referential constraint based on substring of value in EF4? - c#

In EF4 is it possible to have a referential contstraint which is based upon just a substring of a value?
e.g.
Ref table:
Code: varchar(5)
Desc: varchar(50)
Main Table:
Code: varchar(6)
Data1:
Data2: etc...
I would like to have a constraint where MainTable.Code.Substring(0,5) > RefTable.Code
Is that possible?

No this is not possible and I doubt that you can create such relation in database - EF follows same rules as relational database.
Edit: Actually there can be a way to achieve that if you try to represent it as a query inside QueryView.

Related

Create and use table referencing two rows of one other table

A tale of three tables: using Entity Framework 6, I need a user-editable table Disallow to store conflicts between rows of another table Option of type Technology.
Like this:
Technology:
ID, PK, [int], not null
Description, nvarchar(40), not null
Option:
ID, PK, [int], not null
Name, nvarchar(20), not null
ADD CONSTRAINT (FK_Tech) FOREIGN KEY [ID] REFERENCES [Technology] (ID)
Disallow:
ID1, [int], not null
ID2, [int], not null
PRIMARY KEY (ID1, ID2) ASC
ADD CONSTRAINT [FK_Valid1] FOREIGN KEY [ID1] REFERENCES [Option] (ID)
ADD CONSTRAING (FK_Valid2) FOREIGN KEY [ID2] REFERENCES [Option] (ID)
As I understand it, after importing the database into the model the user should be able to add records from the EF model so that e can specify that when choosing technology options, it should be disallowed to choose two particular options together.
I have spent much time looking for help on using multiple foreign keys into a single table and was able to create the table successfully in SQL Server and I think I understand the issues there.
But when I attempt to import into EF, an association is shown, on the Options table, but nothing else. How can I add rows if there is no mapping to the table? And then I found a link telling me that there is no way to reference a foreign key. So I added two additional fields, but even after numerous attempts -- following the advice of many links on THAT topic -- failed to bring the table into the model. How can I ensure (1) that the IDs added to the Disallow table are found in Option, and (2) still reference them in EF?
Or perhaps better said, how can I accomplish what I want: rows of conflicts that my code will use to limit the selection of options?

How to solve bad database design with Entity Framework?

I apologize for the strange question; it is hard to put into words. I am forced to work with a database of questionable design and I would like to solve data access issues with the Entity Framework. I am at a loss how to treat this type of design in an object oriented way.
The Item table is the problem. It has fields that may contain different types of data, ranging from Size to Lot Numbers to SO numbers, etc. The name of the field is determined by the ItemDef table, which links to a ItemDefValue table with the actual field names. The tables have been simplified for demonstration purposes.
Create Table Item
(
ItemKey int Primary Key not null,
ItemID1 varchar(100) null,
ItemID2 varchar(100) null,
ItemID3 varchar(100) null,
ItemID4 varchar(100) null,
ItemDefKey int not null --foreign key to ItemDef table
);
Create Table ItemDef
(
ItemDefKey int Primary Key not null,
CustomerKey int not null , -- foreign key to cusotmer table
);
Create Table ItemDefValue
(
FieldCode small not null,
Title varchar(50) not null
ItemDefKey int not null - foreign key to ItemDef table
);
I have solved this problem with DataSets and DataTables by renaming columns based on the ItemDefValue, so I am not looking for a table-based solution. I would like to avoid this type of table-based logic, especially since I am not fond of DataSets and would rather accomplish data access using the Entity Framework.
I would appreciate advise from anyone that has dealt with this kind of problem before. I would specifically like any suggestions on how to treat this kind of database design in an object oriented way, preferably using the Entity Framework.
And if you think there is no other solution than to re-design the database than I will take that advise as well.
Thanks.
Messy! A restructure would definitely be best.
But, how about creating views that represent the way you'd like the tables to be organised at an object level - and then with EF use those views rather than the tables directly. You'd need to function map the insert/update/delete to stored procedures for dealing with the real tables, but at least from EF side of things you'd be dealing with a decently organised set of entities rather than those tables ...

entity framework not working on table without identity column

I have the following table:
create table tbl
(
id int identity(1,1),
val varchar(100)
)
Now when i use Entity Framework to map objects to this table, it works, however when i change the table definition as follows:
create table tbl1
(
id int,
val varchar(100)
)
Entity Framework does not maps objects to this table. Any clue as to why is this happening would be appreciated.
Entity Framework requires a Primary Key to generate a model from the database. If there is no Primary Key on a table it will simply select the non-nullable columns as a concatenated primary key and the Entity will be read/only.
In your first table identity definition makes your id column non-nullable so you were able to create an Entity. You should have seen this message while adding that table:
"The table/view 'tbl1' does not have a primary key defined. The key
has been inferred and the definition was created as a read-only
table/view."
In your second table however there is no non-nullable column and EF cannot create an Entity for it. See the message when you try to add it:
"The table/view 'tbl1' does not have a primary key defined and no
valid primary key could be inferred. This table/view has been
excluded. To use the entity, you will need to review your schema, add
the correct keys, and uncomment it."
Entity frameworks generally need a way to distinguish between two records in a table and so require a ID/Key discriminator which need not be a primary key constraint or a unique key constraint or an identity at the DB layer. But this discriminator, a column or a set of columns, should help the entity framework identify a record uniquely and distinguish it from other records. So, you need to define such a discriminator in your entity class at the C# layer.

Entity Framework bug, insert command generation

I am working with PostgreSql DB using Entity Framework:
When I add new item into DB it generates strange code:
INSERT INTO (SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact")
("person_id","contact_id")
VALUES (cast(141792 as int8),cast(289406040 as int8))
So it add
SELECT "person_contact"."person_id" AS "person_id",
"person_contact"."contact_id" AS "contact_id"
FROM "public"."person_contact" AS "person_contact"
instead of table name "public"."person_contact"
How to resolve this Entity Framework bug ???
UPD: Same issue when I try to delete "person_contact" entry. In delete statement instead of table name - select query.
There are several ways to try and fix this:
Firstly, it could be that your model has become corrupt. You could try deleting the model and recreating it. Also see my answer to this question: SQL Server foreign keys messing with entity framework model
Secondly, you say that it only happens with this table. Is there anything special about this table.
Thirdly, you could try a different .net connector for ProgressSQL, see: http://www.devart.com/dotconnect/entityframework.html
These are listed in the order that I would try them.
Most likely you forgot to create primary key on this table.
I've had the same problem and the solution in my case was very simple. The problem was that I had a column named "id", but I forgot to make it Primary Key. The moment I set it as Primary Key everything was OK.
It is very strange, because EF, normaly won't import table without primary key, but when you have column named "id" it assumes that it is a primary key.
The structure of my table was:
*DROP TABLE IF EXISTS "public"."fact_season_tickets";
CREATE TABLE "public"."fact_season_tickets" (
"id" int8 DEFAULT nextval('fact_season_tickets_id_seq'::regclass) NOT NULL,
"season_ticket_id" int8 NOT NULL,
"date_key" int4 NOT NULL,
"station_id" int4 NOT NULL,
"amount" numeric(18,2) DEFAULT 0 NOT NULL,
"status" int4 NOT NULL
)
WITH (OIDS=FALSE)*
The generated by NpgSql INSERT statement was:
*INSERT INTO (SELECT "fact_season_tickets"."id",
"fact_season_tickets"."season_ticket_id",+
"fact_season_tickets"."date_key",
"fact_season_tickets"."station_id",
"fact_season_tickets"."amount",
"fact_season_tickets"."status"
FROM "public"."fact_season_tickets" AS "fact_season_tickets")
("season_ticket_id","date_key","station_id","amount","status")
VALUES (510::int8,20150630,2,18.00::numeric,1)
RETURNING "id"*
The solution was just creating a primary key:
*ALTER TABLE "public"."fact_season_tickets" ADD PRIMARY KEY ("id");*

Violation of PRIMARY KEY constraint Cannot insert duplicate key in object . In C#.net....Visual Studio 2010...framework 3.5

I'm Developing a small windows application in C#.net in Visual Studio 2010 with framework 3.5. I use LinqToSql for database manipulation.
table name: cprofile
Fields of the table are:
custid int (primary key),
custname varchar(50),
address nvarchar(MAX),
mobileno nchar(10)
So i have changed the 'Is identity' property of the 'cust id' to 'yes'. It automatically changes other 2 sub properties.
Identity Increment = 1
Identity Seed = 1,
After these changes have been made in the table, it throws error when I try to save a new record.
"Cannot insert explicit value for identity column in table 'cprofile'
when IDENTITY_INSERT is set to OFF."
Not too familiar with L2S, but I'd say Daniel is correct: update your model (usually on a context menu somewhere) from the DB. That should prevent it from attempting to insert a value into your auto-incrementing ID column.
I believe there may be a way to have it set IDENTIY_INSERT ON, but I highly recommend against it.
If your table should not be in charge of setting the CustomerId (say, the business has some method of making that determination (especially in a non-linear way), leave your Customer Id column as the PK, but remove the Identity specificaiton from the column.
If you're trying to use the same insert statement you were using before, you can no longer do that. I'm not sure how it's done in the C# side of it, but in SQL, you'd have to run statements to turn identity_insert on, then run your statement. Because you changed the column to identity, the table makes sure the next entry is always 1 number higher than the previous. Because of this, you can't simply insert values into it. If you want the table to create the identity value for you, simply remove it. If my explanation doesn't help, hopefully this will.
Table Definition (Table1)
Col1 Identity
Col2 varchar(50)
Col3 bool
Insert statement before identity
INSERT INTO Table1 VALUES (1, 'Test', TRUE)
Insert statement after identity
INSERT INTO Table1 VALUES ('Test', TRUE)
When identity is on, you cannot specify the value without turning on identity_edit. I'll see if I can find how to do that in Linq.
EDIT: I also like what Daniel said. Didn't think about that.

Categories

Resources