How should I declare smallmoney in Entity Framework code first? - entity-framework-6

I have been using the following property in my entity
public decimal smallamount { get; set; }
It persists to a SQL Server column of type smallmoney.
I get a warning
No type was specified for the decimal column "smallamount" on entity type jobline.
This will cause values to be silently truncated if they do not fit in the default precision and scale.
Explicitly specify the SQL Server column type that can accommodate all the values using 'ForHasColumnType()'.
I gather I can use a column attribute
For example
[Column(TypeName = "decimal(10, 2)")]
Or alternatively use the modelbuilder HasPrecision property.
But where can I find out what precision I should use?

Related

string or binary data would be truncated. when large string is inserted in a field

in my model in asp.net mvc5 website there is field name
[Display(Name = "Detail (A-Z)")]
[StringLength(int.MaxValue)]
[AllowHtml]
public string Description { get; set; }
i want to have maximum string size for this field . i used StringLength(int.Maxvalue)
when i enter large string(not very large) it gives error .on small string it works fine.
i changed the removed the stringlength data annotation but still gives the same error.i think stringlangth should allow maximum characters.
It is not the problem with the Server side code. The issue is with the database's field's length. You are sending longer string than the DB column can hold. Thus the error is raised for longer strings.
Do the followings:
[StringLength(X)] here x is the length of the column in the DB.
If you want the input to be max in length which is required in case of html inputs, then remove the StringLength property from the model. Which would not restrict the input length. And then change the DB column to be Varchar (Max).

The field Pdf must be a string or array type with a maximum length of '4000'

I'm struggling, trying to save a byte array to my database, using EF (code first), MVC.NET.
var bytes = File.ReadAllBytes(filePath);
myObjectToSave.Pdf = bytes;
The message I get is
The field Pdf must be a string or array type with a maximum length of '4000'.
The PDF is 20kb!
Research on SO shows a few things about strings, but in my case, my object is
public byte[] Pdf {get; set;}
I am already using an array!
I am using SQL CE but I don't understand what to do to solve this issue.
check the EF Model it should be simply that a property on the Entity you're updating has the Max Length attribute
same problem
MaxLength attribute : check here
make sure that field set to varbinary(max) in sql

In MVC, how can I retrieve records from database matching a range of string serial numbers that include numbers?

I have an MVC application that uses Code First Entity Framework.
I have records in my database for serial numbers that are strings, and a combination of letters and numbers. The last 4 are always the number part.
I am trying to retrieve all records in between range A and B, so for example from SERIAL-NO-0020 to SERIAL-NO-0050
I cannot convert the string number part to an integer because Linq To Entities doesn't support it. So as an example to get all records with a serial number higher than 20, this doesn't work:
var records = context.SerialNumbers.Where(m => Convert.ToDecimal(m.SerialNo.Substring(10, 4)) > 20).ToList();
Is there a way to do this without first pulling all the records from the database and filtering further?
Convert.ToDecimal can't be translated to SQL when using it with Linq to Entities.
You can create a stored procedure that query the data so you can do anyahting that can't be done by EF.
Another solution is to create a computed column.
First, add a new property. Let name it SerialId in your SerialNumber entity.
Second, Decorate that property with a data annotation:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
or use fluent configuration if you want:
modelBuilder.Entity<SerialNumber>().Property(t => t.SerialId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Third, Add new EF migration and in the generated migration file, just update it by passing a new value to defaultValueSql parameter liek below:
public override void Up()
{
AddColumn(
"dbo.SerialNumber",
"SerialId",
c => c.Int(nullable: false, defaultValueSql: "CAST(SUBSTRING(SerialNo, 11, 4) AS INT)"));
}
The modification says that each line of SerialNumber table has a generated column and its value is calculated by using this SQL statement => CAST(SUBSTRING(SerialNo, 11, 4) AS INT)
You can update your database by running ef command => update-databse.
Finally, you can change your Linq to Entities like below and you don't need any conversion:
var records = context.SerialNumbers.Where(m => m.SerialId > 20).ToList();
Instead of Writing Queries you can write SP and access this SP (Stored Proceure) with the help of Linq.
In SP you can split the record first and then compare. It will also take less time and increase the performance.

Grails alters my table using not null instead of null

I'm developing a personal project with grails in order to learn this powerful tool.
I have encountered this problem when adding two new fields (x,y) to my domain class "Post":
class Post {
long id;
Date creationDate;
String text;
byte[] image;
Style style;
long likeCount;
long dislikeCount;
User owner;
//coordinates on the wall
int x;
int y;
//this is probably to remove
static hasMany = [judgment : Judgment];
static constraints = {
text(nullable:true, maxSize:5000);
image(nullable:true, maxSize:1000000);
creationDate(nullable:true);
x(nullable:true);
y(nullable:true);
}
}
I added x and y after I create some data (Post records) on my postgres database.
But when I run-app in grails console this error comes up:
| Error 2012-03-04 12:04:23,670 [pool-5-thread-1] ERROR hbm2ddl.SchemaUpdate - Unsuccessful: alter table post add column x int4 not null
| Error 2012-03-04 12:04:23,672 [pool-5-thread-1] ERROR hbm2ddl.SchemaUpdate - ERROR: column "x" contains null values
this is very strange because i declared in constraint x,y to be nullable.. so why grails try to alter my table declaring x and y to be not null?
They're primitive int fields, so nullable doesn't make sense. You can't store a null value in the class instance, and if you have a null value in the database there's no sensible default conversion to an int value. You may consider 0 a sensible value for null, but 0 and null aren't equivalent in general.
If you want to allow null values for primitive numbers (int, long, etc.) or for boolean use the non-primitive Object classes Integer, Long, Boolean, etc. Another problem with primitive types is validation. Since they default to 0 (or false for boolean) you can't know whether the user chose 0 or false or if they didn't make a choice at all and you just have the default values from the constructor. So making them non-primitive leaves them null and you can know whether they made a choice or not.
Also, unrelated - you don't need to declare the id field, since Grails adds one for you anyway. And lose the semicolons ;)

How can I Alias Data in a WebGrid

I have an existing database that I can't change. I have a column of type int that has various numbers that mean something.
This something would be a string. For example, 1="dog", 2="cat", 3="bird". There are a dozen or so integers to deal with.
I'm using ASP.NET MVC 3 with EF 4.1 and have a WebGrid binding to the Model. Is there a way to alias the data for these integers listed in the WebGrid to display the string value that mean something to the user?
Any help on this would be greatly appreciated!
Add an enum to your Model:
public enum foo
{
dog = 1, cat, bird //etc
}
Hopefully, you are using ViewModels. If you are, add a property for the enum:
public foo thing {get;set;}
And set the value of thing based on the integer value you get from the database:
Model m = new Model{number = 3};
m.thing = (foo) m.number;
Or you could create a helper and use that within the format parameter to set a value based on the integer, or you could use JavaScript/jQuery to alter the values from ints to strings once they have been rendered to the browser.

Resources