Many to many to many relationships with EF4 and Code First - entity-framework

I've got a problem I can't figure out how to express with CTP5 of Code First and EF4.
EDIT: Added my old schema at the bottom that I'd like to replicate through CF
Here's my specific scenario:
A Team is an abstract concept; it should exist with a specific set of players, in a specific division, in a specific season.
A concrete example of this in action from the NFL:
1996 (season) AFC Central (division) Houston Oilers (team)
1997 (season) AFC Central (division) Tennessee Oilers (team)
1999 (season) AFC Central (division) Tennessee Titans (team)
2002 (season) AFC South (division) Tennessee Titans (team)
These are all the same team. I want to be able to do the following:
// Titans team id = 17
var myTeam = myContext.Teams.Single(t => t.Id == 17)
// display players
foreach (var p in myTeam.Seasons[1999].Players)
{
// Do something with the p here
}
// Display current division
Response.Write(myTeam.Seasons[2002].Division.Name);
I'm not sure of the specific query syntax within an ICollection member variable of myTeam.Seasons, but the concept should be the same none the less.
Can anyone shed some light on how you'd express this concept through CF in EF4 CF CTP5?
How would you express this through Code First?
Current SQL tables
CREATE TABLE dbo.Season
(
Id INT IDENTITY(1,1) NOT NULL,
LeagueId INT NOT NULL,
[Name] NVARCHAR(50) NOT NULL,
[Year] CHAR(4) NOT NULL,
PrevSeasonId INT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Season WITH NOCHECK ADD
CONSTRAINT PK_Season PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
CREATE TABLE dbo.Division
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Division WITH NOCHECK ADD
CONSTRAINT PK_Division PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY];
// Key Relation Table
CREATE TABLE dbo.DivisionsInSeason
(
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
Commissioner UNIQUEIDENTIFIER NOT NULL,
ParentDivId INT NULL
) ON [PRIMARY];
// Primary Key
ALTER TABLE dbo.DivisionsInSeason WITH NOCHECK ADD
CONSTRAINT PK_DivisionsInSeason PRIMARY KEY NONCLUSTERED (DivisionId, SeasonId) ON [PRIMARY] ;
// Foreign Keys
ALTER TABLE dbo.DivisionsInSeason WITH CHECK ADD
CONSTRAINT FK_DivisionsInSeason_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_DivisionsInSeason_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_DivisionsInSeason_User FOREIGN KEY(Commissioner) REFERENCES dbo.[User](Id);
CREATE TABLE dbo.Team
(
Id INT IDENTITY(1,1) NOT NULL,
DefaultName NVARCHAR(50) NOT NULL,
DefShortName NCHAR(3) NULL
) ON [PRIMARY];
// Primary key
ALTER TABLE dbo.Team WITH NOCHECK ADD
CONSTRAINT PK_Team PRIMARY KEY NONCLUSTERED (Id) ON [PRIMARY] ;
// Key relationship table
CREATE TABLE dbo.TeamsInDivision
(
TeamId INT NOT NULL,
DivisionId INT NOT NULL,
SeasonId INT NOT NULL,
GeneralManager UNIQUEIDENTIFIER NOT NULL,
Name NVARCHAR(50) NOT NULL,
ShortName NCHAR(3) NULL
) ON [PRIMARY];
// Check Constraints
ALTER TABLE dbo.TeamsInDivision ADD
CONSTRAINT PK_TeamsInDivision PRIMARY KEY NONCLUSTERED (TeamId, DivisionId, SeasonId) ON [PRIMARY];
// Foreign Keys
ALTER TABLE dbo.TeamsInDivision WITH CHECK ADD
CONSTRAINT FK_TeamsInDivision_Team FOREIGN KEY(TeamId) REFERENCES dbo.Team(Id),
CONSTRAINT FK_TeamsInDivision_Division FOREIGN KEY(DivisionId) REFERENCES dbo.Division(Id),
CONSTRAINT FK_TeamsInDivision_Season FOREIGN KEY(SeasonId) REFERENCES dbo.Season(Id),
CONSTRAINT FK_TeamsInDivision_User FOREIGN KEY(GeneralManager) REFERENCES dbo.[User](Id);

Maybe this could be usefull
http://blogs.microsoft.co.il/blogs/gilf/archive/2011/08/01/creating-a-many-to-many-mapping-using-code-first.aspx

Related

Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'questions_ibfk_1' in the referenced table 'category'

cannot add foreign key constraint to table
create table users
(
user_id int auto_increment primary key not null,
username varchar(50) unique null ,
email varchar(50) unique ,
passwords varchar(50) not null,
login_status boolean not null
);
create table category (
category_id int primary key not null,
category_name varchar(50) not null
);
create table answers (
id_answer int auto_increment primary key not null,
answer boolean not null
);
create table questions (
question_id int primary key not null,
category_name varchar(50) not null,
content varchar(50) not null ,
foreign key (category_name) references category (category_name)
);
You get this error because there's no index on category_name in the category table. Change that CREATE statement as follows:
create table category (
category_id int primary key not null,
category_name varchar(50) not null,
KEY category_name_index (category_name)
);
From the docs (8.0 version, but the statement is true for older versions):
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Also, you're using a varchar(50) as your foreign key, which is not usually a great idea for a variety of reasons. You probably want to use a numeric value, such as category_id, instead.

ER diagram - Are the relations and cardinalities correct?

I'm building a diagram on LucidChart for a Brewery that sells and makes beer in 1 location. I watched some videos on how to design an ER model. Wondering if this is correct or if I made any mistakes. Also what exactly is "mapping" for when talking about ER models?
Here is my ER model:
Also Cardinality Legend I went off of from LucidChart:
what exactly is "mapping" for when talking about ER models?
Within the context of a data model, the term "mapping" is a name for the process of converting a data model into the SQL DDL that can then be used to create a database schema in a database management system such as MySQL, SQL Server, Oracle and so on.
To the best of my knowledge, you can't "map" with tools such as Visio and LucidChart because these tools are not designed for data modeling. They are designed to mechanise the process of drawing diagrams. (A proper data model contains a lot more than pictures)
As an example, I used your ER diagram to design an object-role model using the free NORMA tool.The following diagrams show:
The object-role model
The logical model (It took a few milliseconds to generate the logical model from the object-role model.)
The SQL DDL that I "mapped" from the object-role model (It took a few seconds to map the object-role model into SQL DDL.)
I use SQL Server Management Studio so I can copy and paste the T-SQL version of the DDL into the "New Query" window and generate the database tables in a few seconds.
This is the object-role model (split into pages)
This is the logical model (auto generated) Note that unlike your model, there is only one "Address" table in the logical model.
This is the SQL DDL for MySQL Server (auto generated)
CREATE TABLE Brewery
(
breweryNr INT NOT NULL,
addressNr INT NOT NULL,
breweryName CHAR(63) NOT NULL,
CONSTRAINT Brewery_PK PRIMARY KEY(breweryNr)
);
CREATE TABLE Address
(
addressNr INT NOT NULL,
country CHAR(63) NOT NULL,
street CHAR(63) NOT NULL,
town CHAR(63) NOT NULL,
zipCode CHAR(63) NOT NULL,
CONSTRAINT Address_PK PRIMARY KEY(addressNr)
);
CREATE TABLE Beer
(
beerType CHAR(63) NOT NULL,
alcoholPercent INT NOT NULL,
beerAmountLitres CHAR(63) NOT NULL,
beerID CHAR(63) NOT NULL,
beerPrice CHAR(63) NOT NULL,
kegNr INT NOT NULL,
CONSTRAINT Beer_PK PRIMARY KEY(beerType)
);
CREATE TABLE BreweryMakesBeer
(
beerType CHAR(63) NOT NULL,
breweryNr INT NOT NULL,
CONSTRAINT BreweryMakesBeer_PK PRIMARY KEY(breweryNr, beerType)
);
CREATE TABLE Keg
(
kegNr INT NOT NULL,
kegState CHAR(63) NOT NULL,
CONSTRAINT Keg_PK PRIMARY KEY(kegNr)
);
CREATE TABLE Employee
(
employeeNr INT NOT NULL,
addressNr INT NOT NULL,
birthDate INT NOT NULL,
breweryNr INT NOT NULL,
firstName CHAR(63) NOT NULL,
lastName CHAR(63) NOT NULL,
salary DECIMAL(6,4) NOT NULL,
SSN CHAR(63) NOT NULL,
middleInt CHAR(63),
CONSTRAINT Employee_PK PRIMARY KEY(employeeNr)
);
CREATE TABLE Distributor
(
distributorNr INT NOT NULL,
brewingIngredientNr INT NOT NULL,
CONSTRAINT Distributor_PK PRIMARY KEY(distributorNr)
);
CREATE TABLE BrewingIngredient
(
brewingIngredientNr INT NOT NULL,
ingredientName CHAR(63) NOT NULL,
CONSTRAINT BrewingIngredient_PK PRIMARY KEY(brewingIngredientNr)
);
CREATE TABLE IngredientSupplier
(
ingredientSupplierNr INT NOT NULL,
addressNr INT NOT NULL,
CONSTRAINT IngredientSupplier_PK PRIMARY KEY(ingredientSupplierNr)
);
CREATE TABLE IngredientSupply
(
brewingIngredientNr INT NOT NULL,
ingredientSupplierNr INT NOT NULL,
CONSTRAINT IngredientSupply_PK PRIMARY KEY(brewingIngredientNr, ingredientSupplierNr)
);
ALTER TABLE Brewery ADD CONSTRAINT Brewery_FK FOREIGN KEY (addressNr) REFERENCES Address (addressNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE Beer ADD CONSTRAINT Beer_FK FOREIGN KEY (kegNr) REFERENCES Keg (kegNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE BreweryMakesBeer ADD CONSTRAINT BreweryMakesBeer_FK1 FOREIGN KEY (breweryNr) REFERENCES Brewery (breweryNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE BreweryMakesBeer ADD CONSTRAINT BreweryMakesBeer_FK2 FOREIGN KEY (beerType) REFERENCES Beer (beerType) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE Employee ADD CONSTRAINT Employee_FK1 FOREIGN KEY (breweryNr) REFERENCES Brewery (breweryNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE Employee ADD CONSTRAINT Employee_FK2 FOREIGN KEY (addressNr) REFERENCES Address (addressNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE Distributor ADD CONSTRAINT Distributor_FK FOREIGN KEY (brewingIngredientNr) REFERENCES BrewingIngredient (brewingIngredientNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE IngredientSupplier ADD CONSTRAINT IngredientSupplier_FK FOREIGN KEY (addressNr) REFERENCES Address (addressNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE IngredientSupply ADD CONSTRAINT IngredientSupply_FK1 FOREIGN KEY (brewingIngredientNr) REFERENCES BrewingIngredient (brewingIngredientNr) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE IngredientSupply ADD CONSTRAINT IngredientSupply_FK2 FOREIGN KEY (ingredientSupplierNr) REFERENCES IngredientSupplier (ingredientSupplierNr) ON DELETE RESTRICT ON UPDATE RESTRICT;

EF 6.2 Referential constraint Issue

I created a SQLite 3 db from an existing SQL Express DB. The primary keys in the new SQLite db are type INTEGER, the foreign keys are type int. EF throws a 13101 error.
Example
CREATE TABLE Test (
TestID INTEGER NOT NULL,
TestName NVARCHAR (50),
TestTypeId INT,
TestConfigId INT,
Description NVARCHAR (255),
NumberOfRuns INT,
Modified ROWVERSION NOT NULL,
CONSTRAINT PK_Tests PRIMARY KEY (
TestID
),
FOREIGN KEY (
TestConfigId
)
REFERENCES TestConfiguration (TestConfigID) ON DELETE NO ACTION
ON UPDATE NO ACTION,
FOREIGN KEY (
TestTypeId
)
REFERENCES TestType (TestTypeID) ON DELETE NO ACTION
ON UPDATE NO ACTION
);
CREATE TABLE TestType (
TestTypeID INTEGER NOT NULL,
TestTypeName NVARCHAR (50) NOT NULL,
Description NVARCHAR (50) NOT NULL,
Modified ROWVERSION NOT NULL,
CONSTRAINT PK_TestTypes PRIMARY KEY (
TestTypeID
)
);
In table Test, TestTypeId is an int and a FK, but in table TestTypes TestTypeID is an INTEGER and EF 6.2says they are of different types.
So is the answer to change all the PK's to int and make them AUTO_INCREMENT or change all the PK's to INTEGER?
Thanks,
Doug

Find cause of error "constraint xxxx is not a foreign key constraint" in Postgresql

I have defined these tables:
CREATE TABLE "public".category (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE UNIQUE INDEX category_name ON "public".category (name);
CREATE TABLE "public".clusters (id BIGSERIAL NOT NULL, name varchar(255) NOT NULL, PRIMARY KEY (id));
CREATE INDEX clusters_name ON "public".clusters (name);
CREATE TABLE "public".keywords (id BIGSERIAL NOT NULL, text varchar(255) NOT NULL, category_id int8 NOT NULL, top_results int4, cluster_id int8, month_requests int4, click_cost float8, PRIMARY KEY (id));
CREATE INDEX keywords_text ON "public".keywords (text);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords488682 FOREIGN KEY (cluster_id) REFERENCES "public".clusters (id);
ALTER TABLE "public".keywords ADD CONSTRAINT FKkeywords446526 FOREIGN KEY (category_id) REFERENCES "public".category (id) ON UPDATE CASCADE ON DELETE CASCADE;
added one record to category table:
INSERT INTO "public".category(id, name) VALUES (1, 'Test');
And now when I try to add record to keyword table
insert into "public"."keywords" ( "category_id", "text") values ( 1, 'testkey')
I got error:
ERROR: constraint 16959 is not a foreign key constraint
When I do
select * FROM pg_constraint;
I can't see constraint with this id. I can't understand what is the cause of this problem.

Add association in entity framework 5

In a legacy product I have the following two tables:
Create Table City (
Id int identity not null,
Gid uniqueidentifier not null,
Name varchar(25) not null,
constraint PK_City Primary Key(Id)
)
Create Table CityExtra(
Gid uniqueidentifier not null,
CityGid uniqueidentifier not null,
ExtraName varchar(25) not null,
constraint PK_CityExtra Primary Key(Gid)
)
In the EF editor I would like to create a one-one relation between these two entities.
Creating the association is not a problem, but how do I create the association mappings between City.Gid and CityExtra.CityGid (City.Gid is not a key)?
Or is this not possible?