Ran into a small problem while working on EF 6 Database first approach.
When I try to insert a value into the key field of a table which is not set to be the Identity, I receive the following exception:
Cannot insert the value NULL into column 'emp_main_id',column does not allow nulls. INSERT fails.
The statement has been terminated.
I added the following code in the entity class to avoid the error
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int emp_main_id { get; set; }
but still could not get it working.
Below is the script to create the db table
CREATE TABLE [dbo].[EmployeesMain] (
[emp_main_id] INT NOT NULL,
[emp_main_first] NVARCHAR (40) NOT NULL,
[emp_main_middle] NVARCHAR (40) NULL,
[emp_main_last] NVARCHAR (40) NOT NULL,
[emp_main_dob] DATE NOT NULL,
[emp_main_gender] INT DEFAULT ((1)) NOT NULL,
[emp_main_type] INT DEFAULT ((0)) NOT NULL,
[emp_main_email] NVARCHAR (150) NOT NULL,
[emp_main_password] NVARCHAR (MAX) NOT NULL,
[emp_main_designation] NVARCHAR (150) NULL,
[emp_main_skill] NVARCHAR (MAX) NULL,
[emp_main_contract] INT DEFAULT ((0)) NOT NULL,
[emp_main_lead] NVARCHAR (81) NULL,
[emp_main_img] NVARCHAR (MAX) NULL,
[emp_main_doj] DATE DEFAULT ('01-JAN-2012') NULL,
CONSTRAINT [emp_main_primary_key] PRIMARY KEY ([emp_main_id])
);
Any help on this will be appreciated.
Problem is you are trying to insert NULL value to a Primary Key
column i.e emp_main_id.
Primary Key doesn't allow to insert NULL values or duplicate values.
If you want to insert NULL values remove Primary Key constraint.
Decided to write the answer myself.
The problem was, since I had set the field as an identity earlier, the values for the field were being generated automatically. Even after removing the identity and updating the model from the database, this was not reset.
So what I had to do was,
Go to the .edmx file.
Right click on the property "emp_main_id"
Click on Properties
Set StoreGeneratedPatter to None
Save the model and rebuild the solution
That's it. it gives me a non-identity key, with all the other constraints along with the option to explicitly enter a value for the field. Peace :)
Related
I have a requirement to create a calculated column in a database table using EF6 code first. Below is the table definition I am trying to generate:
CREATE TABLE [Dim].[Account](
[pkAccount] [int] IDENTITY(1,1) NOT NULL,
[Account] [nvarchar](20) NULL,
[AccountDescription] [nvarchar](100) NULL,
[AccountGroup] [nvarchar](20) NULL,
[Chksum] AS checksum([Account],[AccountDescription],[AccountGroup])
) ON [PRIMARY]
I want the Chksum column to calculate a value when a select is executed and not calculated externally and stored as a static value.
I have tried modifying the DbMigration as below using the DefaultValueSql property:
AlterColumn("Dim.Account", "Chksum", b => b.Int(false, false, defaultValueSql: "checksum([Account],[AccountDescription],[AccountGroup])"));
This returned the error The name "[Account]" is not permited in this context.
Is there a way to achieve this?
this is my code for table
CREATE TABLE [dbo].[product] (
[prod_Id] NUMERIC (5) NULL,
[barcode] NUMERIC (13) NULL,
[prod_name] NVARCHAR (50) NULL,
[price] FLOAT (53) NULL,
[stock] NUMERIC (18) NULL,
[cat_id] NCHAR (10) NULL,
[discount] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([prod_Id],[barcode] ASC)
);
I have 2 primary keys prod_id and barcode. I want to make them null as user have choice either to enter prod_id or barcode. Both will not have value at same time. Now please anyone help me how to do it. I tried to make them null it gives syntax error.
Replace primary key with unique
unique CLUSTERED ([prod_Id],[barcode] ASC)
(or)
Give some default value to the columns that are there in the composite primary key.
CREATE TABLE [dbo].[product] (
[prod_Id] NUMERIC (5) default 0,
[barcode] NUMERIC (13) default 0,
[prod_name] NVARCHAR (50) NULL,
[price] FLOAT (53) NULL,
[stock] NUMERIC (18) NULL,
[cat_id] NCHAR (10) NULL,
[discount] FLOAT (53) NULL,
PRIMARY KEY CLUSTERED ([prod_Id],[barcode] ASC)
);
If you are using C# and sending data from C# to SQL server then then you can have validation in place to check if 1 is null then other one must be not null and throw exception/error from there and make both the columns in DB as Unique not primary key. It might help.
In any database table, there is one and only one primary key and that primary key should not be null.
In your case, for each prod_id there will be unique barcode and vise versa. So, it won't make any sense making any one of this as NULL.
instead create 2 table, one containing table_id and other containing barcode and then refer one in another using foreign_key.
I have been working on a project where I have a table with a computed column. When I start sync, it says:
The column "TotalAmount" cannot be modified because it is either a computed column or is the result of a UNION operator
I want to exclude this column from being sync.
I am using C# and Sql Server 2008 R2.
Table Definition:
CREATE TABLE [dbo].[tblFeeDetails](
[RecordId] [bigint] IDENTITY(1,1) NOT NULL,
[SessionId] [int] NOT NULL,
[CourseId] [int] NOT NULL,
[FormNumber] [nvarchar](50) NOT NULL,
[CourseFee] [money] NOT NULL,
[OtherCharges] [money] NOT NULL,
[LateFee] [money] NOT NULL,
[TotalAmount] AS (([CourseFee]+[OtherCharges])+[LateFee]) PERSISTED,
[Status] [bit] NOT NULL
)
You are using SqlSyncAdapterBuilder, correct? Using that, you can specify which columns to track.
am assuming you're using GetDescriptionForTable to retrieve the schema.
you can either, remove the column from the table description Columns collection or you can manually specify which columns you want included in the GetDescriptionForTable...
e.g.,
// Definition for CustomerContact, including the list of columns to include.
Collection columnsToInclude = new Collection();
columnsToInclude.Add("CustomerId");
columnsToInclude.Add("PhoneType");
DbSyncTableDescription customerContactDescription =
SqlSyncDescriptionBuilder.GetDescriptionForTable("Sales.CustomerContact", columnsToInclude, serverConn);
I found in stackoverflow a link who explains this question. I wrote a procedure who does that but the retreived data is not as it's expected by mysql
Here is data that I receive using procedure (this gives an error when I use it for creating a table in this form, the error is syntax error near id int(11))
CREATE TABLE IF NOT EXISTS `atelier`(
`id` int(11) NO PRI auto_increment
`nom` varchar(30) NO UNI
`at_date` date NO
`pax` int(11) NO
`prix` double NO
`vente` double YES
`note` varchar(200) YES
`cr_user` varchar(15) NO
`cr_date` datetime NO
`up_user` varchar(15) YES
`up_date` datetime YES
And here is the data given by phpmyadmin
CREATE TABLE `Atelier` (
`id` int(11) NOT NULL auto_increment,
`nom` varchar(30) NOT NULL,
`date` date NOT NULL,
`pax` int(11) NOT NULL,
`prix` double NOT NULL,
`vente` double default NULL,
`note` varchar(200) default NULL,
`cr_user` varchar(15) NOT NULL,
`cr_date` datetime NOT NULL,
`up_user` varchar(15) default NULL,
`up_date` datetime default NULL,
PRIMARY KEY (`id`)
) ENGINE=Innodb DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
What I want to know should I do translation of YES AND NO within my program or there is a way to obtain it with a query, and with wich query I can obtain info of two last lines given by phpmyadmin.(I think they are usefull for the choose of ENGINE and define the unique and primary keys)
PS:Using c#, and names of the tables I get from another procedure that exist in my program. I don't get it with DESCRIBE. What I receive is between id and up_date.
Here is the link of my procedures MY PROCEDURES
You didn't show the procedure generating this output, but if you replace DESCRIBE in there with SHOW CREATE TABLE I suppose it will work.
Entity Framework v5 looks cool and I try to switch from Linq-to-SQL with existing MSSQL (Azure) database.
but tutorials about EF are too complex to follow.
The database schema is pretty simple as follows (generated by exist db).
Sheets and SheetDetails tables are connected with 1-to-many relationship.
CREATE TABLE [dbo].[Sheets] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Grade] FLOAT (53) CONSTRAINT [DF_Sheets_Grade] DEFAULT ((0)) NOT NULL,
[Title] NVARCHAR (255) CONSTRAINT [DF_Sheets_Title] DEFAULT ('') NOT NULL,
[Description] NVARCHAR (255) NULL,
[Difficulty] SMALLINT CONSTRAINT [DF_Sheets_Difficulty] DEFAULT ((0)) NOT NULL,
[Writer] NVARCHAR (255) CONSTRAINT [DF_Sheets_Writer] DEFAULT ('') NOT NULL,
[Tag] NVARCHAR (255) NULL,
[Duration] FLOAT (53) CONSTRAINT [DF_Sheets_Duration] DEFAULT ((0)) NOT NULL,
[Timestamp] DATETIME CONSTRAINT [DF_Sheets_Timestamp] DEFAULT ((0)) NOT NULL,
[RowVersion] ROWVERSION NOT NULL,
CONSTRAINT [PK_Sheets] PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[SheetDetails] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Score] FLOAT (53) CONSTRAINT [DF_SheetDetails_Score] DEFAULT ((0)) NOT NULL,
[Number] SMALLINT CONSTRAINT [DF_SheetDetails_Number] DEFAULT ((0)) NOT NULL,
[SubNumer] SMALLINT NULL,
[IsRandom] BIT CONSTRAINT [DF_SheetDetails_IsRandom] DEFAULT ((0)) NOT NULL,
[AnswerType] SMALLINT CONSTRAINT [DF_SheetDetails_AnswerType] DEFAULT ((0)) NOT NULL,
[RowVersion] ROWVERSION NOT NULL,
[SheetDetail_Sheet] INT CONSTRAINT [DF_SheetDetails_SheetDetail_Sheet] DEFAULT ((0)) NOT NULL,
[SheetDetail_Question] INT CONSTRAINT [DF_SheetDetails_SheetDetail_Question] DEFAULT ((0)) NOT NULL,
CONSTRAINT [SheetDetail_Sheet] FOREIGN KEY ([SheetDetail_Sheet]) REFERENCES [dbo].[Sheets] ([Id]) ON DELETE CASCADE
);
Note that the FK name is SheetDetail_Sheet in SheetDetails table.
Result diagram is as below.
Next, maybe I need to write EntityTypeConfiguration.
I tried it as question 1.
Question 1.
I wrote model creating configuration as follows but no luck. is it wrong? hard to know how to write right configuration with this simple database model.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new SheetsConfiguration());
base.OnModelCreating(modelBuilder);
}
public class SheetsConfiguration : EntityTypeConfiguration<Sheets>
{
public SheetsConfiguration()
: base()
{
HasKey(p => p.Id);
Property(p => p.Id).HasColumnName("Id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
Property(p => p.RowVersion).IsConcurrencyToken().IsRowVersion();
HasOptional(p => p.SheetDetails).WithMany().Map(x => x.MapKey("SheetDetail_Sheet"));
ToTable("Sheets");
}
}
I execute simple query using
var result = _db.Sheets.Where(sheet => sheet.Id == id).ToList();
And then, I got an error "Invalid column name SheetDetail_Sheet" with executed query as follows.
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Grade] AS [Grade],
[Extent1].[Title] AS [Title],
[Extent1].[Description] AS [Description],
[Extent1].[Difficulty] AS [Difficulty],
[Extent1].[Writer] AS [Writer],
[Extent1].[Tag] AS [Tag],
[Extent1].[Duration] AS [Duration],
[Extent1].[Timestamp] AS [Timestamp],
[Extent1].[RowVersion] AS [RowVersion],
[Extent1].[SheetDetail_Sheet] AS [SheetDetail_Sheet]
FROM [dbo].[Sheets] AS [Extent1]
WHERE [Extent1].[Id] = #p__linq__0
I can understand because SheetDetail_Sheet is just an FK and not exist in the edmx properties and database column.
How can I fix it?
I don't want to edit auto-generated model file because it can be overwritten. maybe it seems to be achieved with EntityTypeConfiguration.
Question 2.
Is there any useful and lightweight reference with the commonly used master-detail database model?
I'm in trouble to start with existing database.
stackoverflow, asp.net, blogs, etc...to many tutorials but hard to find an example like my case.
Thank you.
I'd suggest using Model First to create your database model (though you're using database first). A good article for getting the database model is here. Just ignore the MVC stuff, and stop at "Generating Strongly Typed Entity Classes" as you are using EF5 which will generate the POCO classes for you. The Edmx should handle all of the FKs and properties for you and you won't need to worry about the configurator.