I have 3 tables
Employee(ID,FirstName,LastName) - in which we have all the employees including managers etc.,
EmployeeRole(RoleID,Role) - Here we defined the role of the employees
Project(ProjectName,Manager,Employee,Date..) - here the details of the projects which are assigned to all the employees.
In the project table i have columns like Emmployee,Manager, both the columns are foreign key to the Employee table. The problem is I having input like (Firstname,Lastname), how do i find the id of the emplyee.
Or are the Table Structure is wrong?
When i try to insert data in the Project Table, EmployeeRole table is also updating.It should not update the EMployeeRole Table. its a master data.
Please suggest me the solution?
Your logical data model is not correct (IMHO).
A Project can have many Employees. And a Employee can work on one or more Projects as a particular Role.
So it's a many to many between Employee and Project, with the intersection table having a Role type.
e.g.
CREATE TABLE [dbo].[Employee](
[EmployeeID] [int] NOT NULL,
[FirstName] [nvarchar](50) NOT NULL,
[LastName] [nvarchar](50) NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
))
GO
CREATE TABLE [dbo].[Project](
[ProjectID] [int] NOT NULL,
[ProjectName] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC
))
GO
CREATE TABLE [dbo].[ProjectEmployee](
[ProjectID] [int] NOT NULL,
[EmployeeID] [int] NOT NULL,
[RoleID] [int] NOT NULL,
CONSTRAINT [PK_ProjectEmployee] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC,
[EmployeeID] ASC,
[RoleID] ASC
))
GO
CREATE TABLE [dbo].[Role](
[RoleID] [int] NOT NULL,
[RoleName] [int] NOT NULL,
CONSTRAINT [PK_Role] PRIMARY KEY CLUSTERED
(
[RoleID] ASC
))
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Employee] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeeID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Project] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Project] ([ProjectID])
GO
ALTER TABLE [dbo].[ProjectEmployee] WITH CHECK ADD CONSTRAINT [FK_ProjectEmployee_Role] FOREIGN KEY([RoleID])
REFERENCES [dbo].[Role] ([RoleID])
GO
Then your LinqToEntity looks like this:
// Add a new Role
Role role = new Role();
role.RoleID = 1; // TODO: make identity in database
role.RoleName = "Role 1";
db.Roles.Add(role);
db.SaveChanges();
// Add a new Employee
Employee employee = new Employee();
employee.EmployeeID = 1; // TODO: make identity in database
employee.FirstName = "Carl";
employee.LastName = "Prothman";
db.Employee.Add(employee);
db.SaveChanges();
// Add a new Project
Project project = new Project();
project.ProjectID = 1; // TODO: make identity in database
project.ProjectName = "Create new data model";
db.SaveChanges();
// Add employee to project as role1
ProjectEmployee projectEmployee = new ProjectEmployee();
projectEmployee.ProjectID = project.ProjectID;
projectEmployee.EmployeeID = employee.EmployeeID;
projectEmployee.RoleID = role.RoleID;
db.ProjectEmployees.Add(projectEmployee);
db.SaveChanges();
Related
I try to add new record :
entity.Id = Id;
_bdc.EquifaxAnswers.Add(entity);
_bdc.SaveChanges();
and Id has exactly defined as primary key and Id in code has value ( unique for table).
And EF create sql code for add record:
INSERT [dbo].[EquifaxAnswers]([FileName], [dtSend], [dtDateTime], [RecordsAll], [RecordsCorrect],
[RecordsIncorrect], [ResendedId], [dtEmailAbout], [StartDate], [EndDate])
VALUES (#0, #1, #2, NULL, NULL, NULL, NULL, NULL, #3, #4)
And as we can see there Id does not exist, so _bdc.SaveChanges();create Exception:
Failed in 25 ms with error: Cannot insert the value NULL into column 'Id', table 'Equifax.dbo.EquifaxAnswers'; column does not allow nulls. INSERT fails.
Primary key definition:
public partial class EquifaxAnswers
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
Why EF don't add Id to INSERT and how to resolve this problem ?
UPD:
Table definition script in database:
CREATE TABLE [dbo].[EquifaxAnswers](
[Id] [int] NOT NULL,
[FileName] [nvarchar](300) NOT NULL,
[dtSend] [datetime] NOT NULL,
[dtDateTime] [datetime] NULL,
[RecordsAll] [int] NULL,
[RecordsCorrect] [int] NULL,
[RecordsIncorrect] [int] NULL,
[ResendedId] [int] NULL,
[dtEmailAbout] [datetime] NULL,
[StartDate] [datetime] NULL,
[EndDate] [datetime] NULL,
CONSTRAINT [PK_EquifaxAnswers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
You have specified DatabaseGeneratedOption.None
This means that EF is not expecting the database to generate the Id field, and that you should specify the Id field yourself.
If you want the database to generate the Id field automatically, then alter the column to be an IDENTITY type, and change the code to DatabaseGeneratedOption.Identity
Solution:
modelBuilder.Entity<EquifaxAnswers>()
.Property(a => a.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
If this doesn't work - just uninstall and install again all EF packages ( I don't know why - but this is work for me) for all dependent projects , latest stable version of course.
Reasons:
By convention, EF will assume that primary key properties are automatically generated. So we need to say EF that we will do it by our code. However,this is not clear why doesn't work DataAnnotations like this:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
but fluent API is working well. Perhaps the reason is that I use both.
I have a very large CSV file I have to load on a regular basis that contains time series data. Examples of the headers are below:
| SiteName | Company | Date | ResponseTime | Clicks |
This data comes from a service external to the uploader. SiteName and Company are both string fields. In the database these are normalized. There is a Site table and a Company table:
CREATE TABLE [dbo].[Site] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
CREATE TABLE [dbo].[Company] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
As well as the data table.
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT NOT NULL,
[SiteId] INT NOT NULL,
[DataTime] DATETIME NOT NULL,
CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id]),
CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
)
At around 2 million rows in the CSV file any sort of IO-bound iteration isn't going to work. I need this done in minutes, not days.
My initial thought is that I could pre-load Site and Company into DataTables. I already have the CSV loaded into a datatable in the format that matches the CSV columns. I need to now replace every SiteName with the Id field of Site and every Company with the Id field of Company. What is the quickest, most efficient way to handle this?
If you go with Pre-Loading the Sites and Company's you can get the distinct values using code:
DataView view = new DataView(table);
DataTable distinctCompanyValues = view.ToTable(true, "Company")
DataView view = new DataView(table);
DataTable distinctSiteValues = view.ToTable(true, "Site")
Then load those two DataTables into their SQL Tables using Sql-Bulk-Copy.
Next dump all the data in:
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT DEFAULT 0,
[SiteId] INT DEFAULT 0,
[Company] NVARCHAR(MAX) NOT NULL,
[Site] NVARCHAR(MAX) NOT NULL,
[DataTime] DATETIME NOT NULL
)
Then do an UPDATE to set the Referential Integrity fields:
UPDATE [SiteStatistics] ss SET
[CompanyId] = (SELECT Id FROM [Company] c Where ss.[Company] = c.Name),
[SiteId] = (SELECT Id FROM [Site] s Where ss.[Site] = s.Name)
Add the Foreign Key constraints:
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id])
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
Finally delete the Site & Company name fields from SiteStatistics:
ALTER TABLE [SiteStatistics] DROP COLUMN [Company];
ALTER TABLE [SiteStatistics] DROP COLUMN [Site];
I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
I have created a junction table between two of my tables to create a many to many relationship between them.I am able to save data to them, but can't access that data again. This is written in MVC ASP.NET by the way.
My first table:
CREATE TABLE [dbo].[UserInfo] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR (50) NULL,
[LastName] NVARCHAR (50) NULL,
[Email] NVARCHAR (256) NOT NULL,
[Image] VARBINARY (MAX) NULL,
[Approved] BIT NOT NULL,
[Color] NVARCHAR (10) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
My second table:
CREATE TABLE [dbo].[Events] (
[Id] NVARCHAR (128) NOT NULL,
[Name] NVARCHAR (100) NOT NULL,
[StartDate] DATETIME NULL,
[EndDate] DATETIME NULL,
[Approved] BIT NOT NULL,
[room_id] INT NULL,
[color] NVARCHAR (10) NOT NULL,
[Owner] INT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_Events_Rooms] FOREIGN KEY ([room_id]) REFERENCES [dbo].[Rooms] ([_key])
);
My junction table:
CREATE TABLE [dbo].[UserToEvent] (
[UserId] INT NOT NULL,
[EventId] NVARCHAR (128) NOT NULL,
CONSTRAINT [UserId_EventId_pk] PRIMARY KEY CLUSTERED ([UserId] ASC, [EventId] ASC),
CONSTRAINT [FK_User] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserInfo] ([Id]),
CONSTRAINT [FK_Event] FOREIGN KEY ([EventId]) REFERENCES [dbo].[Events] ([Id])
);
Code to add new relationship:
Event e = await db.Events.FindAsync(id);
string email = User.Identity.Name;
UserInfo user = db.UserInfoes.Where(x => x.Email == email).First();
user.Events.Add(e);
e.UserInfoes.Add(user);
db.Entry(user).State = EntityState.Modified;
db.Entry(e).State = EntityState.Modified;
await db.SaveChangesAsync();
Code to access relationship:
UserInfo user = await db.UserInfoes.FindAsync(id);
List<Events> events = user.Events;
I would expect events to be filled with all events associated with user, but it never has any events.
I have found a work-around which is sufficient to my needs. I added another attribute to my junction table, which then allowed me to access it within my controllers (Since there weren't only two primary keys). From here I was able to gather the data from it just like any other table. Not sure why the above method does not work however. I have used that method before without a hitch. If anyone has an answer, I would love to hear it.
I have created the EF model and then in a Class I have written the following Code to retrieve the value form the DataBase. And store the value in another Table. But it gives me the Error "DATAREADER IS INCompatable" as explained Below..
EmpRole empr = new EmpRole();
empr.EmpId = strEmpId;
string str="select RoleId from RoleName where roleName like '"+strDesignation+"'";
var context= DbAccess.Data.ExecuteStoreQuery<RoleName>(str, null); //Here Showing Error
empr.RoleId = Convert.ToInt16(context);
DbAccess.Data.EmpRoles.AddObject(empr);
DbAccess.Commit();
It's showing the error like:
DataTables were:
CREATE TABLE [dbo].[RoleName](
[SNo] [int] IDENTITY(1,1) NOT NULL,
[RoleId] [smallint] NOT NULL,
[RoleName] [varchar](50) NULL,
CONSTRAINT [PK_RoleName] PRIMARY KEY CLUSTERED
(
[RoleId] ASC
)
CREATE TABLE [dbo].[EmpRoles](
[Sno] [int] IDENTITY(1,1) NOT NULL,
[EmpId] [varchar](8) NOT NULL,
[RoleId] [smallint] NOT NULL,
[ReportingToId] [varchar](8) NULL,
CONSTRAINT [PK_EmpRoles] PRIMARY KEY CLUSTERED
(
[Sno] ASC
)
The data reader is incompatible with the specified 'MyOrgDBModel.RoleName'. A member of the type, 'SNo', does not have a corresponding column in the data reader with the same name.
Please tell me the reasons what to do to execute the sqlQuery.
This is because you are not selecting the SNo column in your select query. As you are populating in RoleName and it has property SNo column should be present in data reader. If you just want the RoleId to be in query then create new type with one property RoleId and use this. Create new type like below
public class CustomRoleName
{
int RoleId { get; set; }
}
Now change your code as follow
EmpRole empr = new EmpRole();
empr.EmpId = strEmpId;
string str="select RoleId from RoleName where roleName like '"+strDesignation+"'";
foreach(CustomRoleName rn in DbAccess.Data.ExecuteStoreQuery<CustomRoleName>(str))
{
empr.RoleId = rn.RoleId ;
DbAccess.Data.EmpRoles.AddObject(empr);
DbAccess.Commit();
break;
}