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;
}
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 table that looks like this.
CREATE TABLE [dbo].[loginInfos]
(
[loginId] INT IDENTITY (1, 1) NOT NULL,
[username] VARCHAR (50) NULL,
[password] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([loginId] ASC)
);
I want to get the username and compare it with a input from a textbox. It will really be a huge help.
var MyDb = new MyDb ("c:\\Data\\MyDb .mdf");
var user = =
(from u in MyDb.loginInfos
where u.username== txtUsername.Text
select u).SingleOrDefault();
// user.username
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 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();
I need a way to get column definition from query result. Right now I'm using SQL Server 2012.
Here is the example scenario, I have two tables which are Event and Attendant whose definitions are below :
CREATE TABLE [dbo].[Event] (
[Id] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
[Description] NVARCHAR (50) NULL,
[StartDate] DATETIME NULL,
[EndDate] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Attendant] (
[Id] INT NOT NULL,
[EventId] INT NOT NULL,
[Name] NVARCHAR (50) NULL,
[Company] NVARCHAR (50) NULL
PRIMARY KEY CLUSTERED ([Id] ASC)
);
And then I have query such as :
SELECT Event.Name as EventName, Attendant.Name as GuestName
FROM Event
INNER JOIN Attendant ON Event.Id = Attendant.EventId
How Can I get the column definition for above example query result? My objective is to generate poco class to represent each record of any query result using c#.
you can use sp_columns sproc to retrieve information about the column definition of a specified table ... like this:
exec sp_columns Attendant
Use sp_columns, it returns column information for the specified objects(tables).
Refer this link for details.
select * from information_schema.columns where table_name = '<tablename>'