I need to write a DB script which creates an association table in my database, creating a parent-child structure within a single table. The resulting model should be something like this:
with n to n relation between the articles.
First of all, let's look at the table creation itself. For the association to work properly in EF, it's essential that primary keys are properly declared. If we don't declare PK for the association table, while the model designer will interpret the association correctly, any attempt to insert into the table will throw error on .SaveChanges().
To create the model specified in the model, we're going to use following code:
create table Article (
articleID int not null identity(1,1),
description varchar(500) not null
)
alter table Article add constraint PK_ArticleID
primary key (articleID)
create table ArticleAssociation (
associatedArticle1ID int not null,
associatedArticle2ID int not null
)
alter table ArticleAssociation add constraint PK_ArticleAssociationID
primary key clustered (associatedArticle1ID, associatedArticle2ID ASC)
alter table ArticleAssociation add constraint FK_AsscociatedArticle1ID
foreign key (associatedArticle1ID) references Article (articleID)
alter table ArticleAssociation add constraint FK_AsscociatedArticle2ID
foreign key (associatedArticle2ID) references Article (articleID)
Now that the structure exists in DB, we can import both Article table and the ArticleAssociation table into our .edmx model. When the import is complete, the tables in model will look like this:
Note the absence of ArticleAssociation table itself, and its generation as an 'Association' type. We may now access the associated objects traditionally via navigation properties:
using (EFTestingEntities efso = new EFTestingEntities())
{
Article article1 = new Article();
article1.description = "hello";
Article article2 = new Article();
article2.description = "world";
efso.Article.Add(article1);
efso.Article.Add(article2);
article1.Article2.Add(article2);
article2.Article1.Add(article1);
efso.SaveChanges();
}
Related
I have a problem where I data for an object, for example billing file, where the data elements are different from client to client. More specifically the number of fields within the data and of different names. I am looking for a solution when working with the objects in C#.
Currently I have created tables for each client. The fields are specific to the client and I use a mapping process when uploading data. I also have dynamic queries in SQL Server to handle all crud processes. It all works pretty well but I believe there is a better solution and I believe saving Json data would be one of them. Pulling the Data I first query the headers of the table and then map the data to those headers for data grids and such. Again, I already have a working solution, but I believe there is a better solution and I am looking for suggestions with examples. By the way, I have thought about dynamic object, in C#, but it would appear you have to know what fields of the object are upfront.
I suggest that you should create mapping table, but there is no need to use something like dynamic sql, here are tables:
create table d_billing_object -- one row here means one field from your question
(
id int not null identity (1, 1) primary key
,name nvarchar(255) not null
)
create table d_billing_client
(
id int not null identity (1, 1) primary key
,name nvarchar(255) not null
)
create table d_billing_mapping
(
billing_client_id int not null
,client_billing_object_id int not null
,billing_object_id int not null
,constraint PK_d_billing_mapping primary key (billing_client_id, client_billing_object_id, billing_object_id)
,constraint FK_d_billing_mapping_d_billing_object foreign key (client_billing_object_id) references d_billing_object (id)
,constraint FK_d_billing_mapping_d_billing_object_2 foreign key (billing_object_id) references d_billing_object (id)
,constraint FK_d_billing_mapping_d_billing_client foreign key (billing_client_id) references d_billing_client (id)
)
After that you just need to create all billing objects and use them in mapping table for all clients you have.
So i have 2 databases. DB1 and DB2. My 'discountCode' table is in DB1 and my 'AspnetUser' table is in DB2. I want to do a many to many table in DB1 between 'discountCode' table and 'AspnetUser' table so i can se that a user already have used a specific discountcode so the user cant use it twice.
I tried doing a normal many to many table between them and it went like this:
CREATE TABLE [dbo].[DiscountUser] (
[DiscountId] INT NOT NULL,
[UserId] nvarchar(128) NOT NULL,
[LanguageId] INT NOT NULL,
CONSTRAINT [PK_DiscountUser] PRIMARY KEY CLUSTERED ([DiscountId] ASC, [UserId] ASC),
CONSTRAINT [FK_DiscountUser_Discount_DiscountId] FOREIGN KEY ([DiscountId]) REFERENCES [dbo].[DiscountCode] ([Id]) ON DELETE CASCADE,
CONSTRAINT [FK_DiscountUser_AspNetUsers_Id] FOREIGN KEY ([UserId]) REFERENCES [db2].dbo.[AspNetUsers] ([id]) ON DELETE CASCADE,
CONSTRAINT [FK_DiscountUser_Language] FOREIGN KEY ([LanguageId]) REFERENCES [dbo].[Language] ([Id])
I then want to update my entity framework modeldesign so i can include this new many to many table in my c# project. So it is important that however i fix this problem i will still be able to use this many to many table like any other entity i have.
First i thought that i would put all the tables in the same database untill i asked about this problem to a friend. My friend did not have much time. All he said to me was do a join in your c# code to bring the 2 tables together. Just ask stackoverflow and they will help you how. So here i am. How do i do a join in m y c# code or is there maybe a better way to get around my problem?
You can't have foreign keys between databases - the error is pretty clear about that. But you can still join them together in a query, you just won't get protection that having them joined by a foreign key gives (e.g. without a foreign key, you can end up with orphaned entries with no data in the foreign table).
If you can have them in a single database that would be best.
I have been trying to handle translations in my database and also Entity Framework. I am generating the following tables but the translate model is not being generated by Entity Framework. I have tried numerous combinations but it won't generate. But, for some reason there is one LanguageTranslate model that IS being generated I think it's because there is just a regular primary key and only one foreign key.
Any ideas are very welcome? Thank you.
CREATE TABLE [dbo].[Merchant]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY
-- Other columns here
)
CREATE TABLE [dbo].[MerchantTranslate]
(
[MerchantId] INT NOT NULL,
[LanguageId] INT NOT NULL,
[Name] NCHAR(50) NOT NULL,
CONSTRAINT [PK_MerchantTranslate]
PRIMARY KEY ([MerchantId], [LanguageId]),
CONSTRAINT [FK_MerchantTranslate_ToMerchant]
FOREIGN KEY ([MerchantId]) REFERENCES [Merchant]([Id]),
CONSTRAINT [FK_MerchantTranslate_ToLanguage]
FOREIGN KEY ([LanguageId]) REFERENCES [Language]([Id])
)
I'm trying to create a table from within visual studio and update my .edmx file inside Visual Studio by right-clicking the file and selecting Update Model from Database.
My table looks like this:
CREATE TABLE [dbo].[tableName] (
[UserId] UNIQUEIDENTIFIER NOT NULL,
[CategoryId] INT NOT NULL,
CONSTRAINT [PK_responsibleUser] PRIMARY KEY NONCLUSTERED ([UserId], [pkID] ASC),
CONSTRAINT [FK_responsibleUser_user] FOREIGN KEY ([UserId]) REFERENCES [dbo].[users] ([UserId]) ON DELETE CASCADE,
CONSTRAINT [FK_categoryResponsibleUser_category] FOREIGN KEY ([CategoryId]) REFERENCES [dbo].[categories] ([CategoryId]) ON DELETE CASCADE
);
This table contains two foreign keys to the tables i want to link. After I run the script "Update Model from Database", a relation between the two tables pops up.
Now Heres the problem: I need EF to generate an instance of my class in Visual studio like this:
public virtual DbSet<tableName> TableIWantToBeGeneratedByEF { get; set; }
As I said, with the current mapping it just creates a relation between two tables. How do I alter my query when creating the table for this to happen? Can this be achieved while using two foreign keys as the primary key or what?
Just open the model designed, select all (ctrl + A), press 'delete' button to delete them, and finally right click and select Update Model from Database. This will force EF to re-generate all model.
(Or just delete all referenced tables so that they are also regenerated)
Almost forgot. It seems that it was the compound primary keys that caused the problem. I changed so both my foreign keys just acted like foreign keys and not as a combined primary key, then created a columnn named Id instead with datatype INT Identity.
Ran the script "Update Model from Database" in .edmx designer and boom, there it was.
I´m trying out entity framework included in VS2010 but ´ve hit a problem with my database/model generated from the graphical interface.
When I do:
user = dataset.UserSet.CreateObject();
user.Id = Guid.NewGuid();
dataset.UserSet.AddObject(user);
dataset.SaveChanges();
{"Cannot insert the value NULL into column 'Id', table 'BarSoc2.dbo.UserSet'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}
The table i´m inserting into looks like so:
-- Creating table 'UserSet'
CREATE TABLE [dbo].[UserSet] (
[Id] uniqueidentifier NOT NULL,
[Name] nvarchar(max) NOT NULL,
[Username] nvarchar(max) NOT NULL,
[Password] nvarchar(max) NOT NULL
);
GO
-- Creating primary key on [Id] in table 'UserSet'
ALTER TABLE [dbo].[UserSet]
ADD CONSTRAINT [PK_UserSet]
PRIMARY KEY CLUSTERED ([Id] ASC);
GO
Am I creating the object in the wrong way or doing something else basic wrong?
On the model for the fields which is defined as key, add the following attribute.
This key which is not marked as IDENTITY in database, Entity Framework give the exception
[Key]
[Display(Name = "Id")]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.DatabaseGeneratedOption.None)]
public int Id { get; set; }
You shouldn't have to set the ID property manually. It should be set automatically when you save. I assume you are using the standard template for Entity Framework, and not the Self-tracking entities template or POCOs template. If so, something along the following lines would seem more appropriate:
User user = new User();
dataset.AddToUsers(user);
dataset.SaveChanges();