I have a web api application using sql server EF 6 code first approach and it's up and running.
Now for a table I want to make a column NULL.
From sql server database side I alter my table definition and able to make the column NULL.
But the class definition has [Required] attribute, which is the reason database save (with null value) still failing even I made database column NULL.
[Required]
[StringLength(512)]
public string Name { get; set; }
I there any solution here?
I understand I need to remove [Required] attribute and this requires a code change. I am looking if some way without code change. this is production .
Removing Required attribute
[StringLength(512)]
public string Name {get;set;}
Related
I have a .Net6 WinForms application using Entity Framework Core 6.0.3 and I am trying to read a simple table from a SQL Server database. I need to rename the column so that it is different in the model than what it is called in the database.
Normally (in EF6, I would add a [Column()] attribute on the property with the new name. However, when I do that it throws an exception reading the data 'Invalid column name' for whatever the new name is.
I have also tried using the modelBuilder and calling the HasColumnName() but get the same error. If I remove the attribute/model builder reference, then no exception occurs, except that I am stuck with the old column name.
[Table("RefTable1")
public partial class SpecialReferenceTable
{
public Int32 Id { get; set;}
[MaxLength(300)]
[Column("NewRefColumn"] // Throws exception Column does not exist: NewRefColumn
public String? OldRefColumn {get;set;}
}
Is there something I am missing with renaming column in Core?
[Column("Column name")] is used for the name of the column in the database table and the name of the property you have is the one you want to change.
Here is the super simple class I'm trying to create.
public class Company
{
public int ID { get; set; }
[Column(TypeName = "VARCHAR(254)")]
[Index]
public string Name { get; set; }
[Index]
public int stupidField { get; set; }
}
My goal was to force Name to be unique, so I added the decoration [Index(IsUnique = true)]. But no unique index was created, so I figured I'll first try to solve the simpler problem of creating any index. Because I read here that indices cannot be created for columns of type varchar(max), I limited the length of the Name field. Still no luck. I even tried a few different syntaxes for limiting the length of the field, but still no index.
To see if something other than string length was at play, I created the integer field stupidField, but I can't index that field either. So now I'm completely out of ideas as to what could be wrong. Please help me!
Check out this screenshot from MS SQL Server Management Studio that shows that my fields are being created but not the indices.
Note: I'm certain migrations are not the issue.
Some of the people I've read about on SO were updating their classes, but those changes were not reflected in the database because of problems with their migrations. That is not relevant here. I delete the database and recreate it every time I make a change. (I even make silly changes like renaming my fields, just to make sure that I can still affect the database.)
Turns out I'm actually using Entity Framework Core, not Entity Framework. In Entity Framework Core, indices cannot be created using attributes, although they can be created using fluent API. See Microsoft's documentation.
How do I add member variables not part of a database column? From searching I saw something called #Transient for java, but nothing for C#. I am also using the entity framework.
[NotMapped]
public string Whatever { get; set; }
Can't believe you haven't found this.
I want to create a DateTime field so that it will have a default GETDATE() once it gets to the database. So I did this:
public class Specialty
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? CreatedDate { get; set; }
// other properties not shown for brevity.
}
So I ran Add-Migration in the PM> console. It resulted in this (not all lines are shown) in the Up function:
AddColumn("dbo.Specialty", "CreatedDate", c => c.DateTime());
I understand that nullable of c.DateTime(...) is true by default, so I understand why it's not specified. BUT where is defaultValueSql: "GETDATE()"?
I know I can put it in manually, but that seems to defeat the purpose of Add-Migration and makes [DatabaseGenerated(DatabaseGeneratedOption.Computed)] useless. I know for a fact that defaultValueSql's default is not "GETDATE()" because it doesn't show up when I look at column properties in SQL Management Studio.
What's missing? Does the name "CreatedDate" violate an EF convention, then? Is there another library that I should have referenced besides System.ComponentModel.DataAnnotations.Schema?
[DatabaseGenerated(DatabaseGeneratedOption.Computed)] is not useless, it tells the Entity Framework that the column is required in the database but is computed by the database. So it knows that it should create the column in a migration and it knows that it should not try to update its value nor insert a value.
What is missing is that you have to add the computation to the database column. And you do that by modifying the migration:
AddColumn("dbo.Specialty",
"CreatedDate",
c => c.DateTime(defaultValueSql: "GETDATE()"));
There is currently no way to specify the sql in a data annotation, and I suspect that there never will be because the sql could be database specific, and is therefore best kept within a migration rather than being allowed to leak into the model definition
I ended up inheriting all entities from a base class, following these instructions.
This means making a custom migration class for the CreatedDate and UpdatedDate column, and it works perfectly with minimal effort.
I'm testing out scaffolding with Entity Framework in Asp.Net MVC 4 (by following this article). I get it to work fine, except that even though my domain object allows null in a field and the database field allows null I get the error message:
Cannot insert the value NULL into column 'IsSuccessful', table 'MyTestProject.Persistence.TestContext.dbo.Prediction'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
My domain object looks like this:
public class Prediction
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public bool? IsSuccessful { get; set; }
}
The generated web page shows IsSuccessful as a drop down box with the choices NotSet, True and False. In the database the column IsSuccessful allows null. Still I get the error message. Everything works fine if I choose True or False (it is saved correctly in the database), but not when I select NotSet.
Surely there must be a way around this?
Some details:
Visual Studio 2012 RC
Asp.Net MVC 4
EntityFramework.dll version 5.0.0.0
That error message looks like it is coming directly from SQL Server. If the server says the column is not nullable, then the column is not nullable. It knows best, after all.
Treble check that the column is really nullable in the database. Also consider:
are you perhaps looking at a different database, with slightly different schema? i.e. one that has not had the correct DDL scripts applied (really easily done)
are you perhaps looking at a different object in the same database? In particular, are you perhaps looking at Halvard.Prediction, where-as the code is looking at dbo.Prediction ?