I have added to my Entity an RowVersion in Code
[Timestamp]
public byte[] Version { get; set; }
and applied to to my Table. In the table it is a "Raw" Type.
My problem is now, that when I call the Entity await context.Orders.... , the System will throw an Error:
InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
There is no mention of the Column that makes problems, but since I have no other byte[] and this is the only change I made, I guess that the Version is the problem.
I have now checked and apparently there is no RowVersion for Oralce? What should I do here? Is there something that can mimic this or should I just add an Date Row and always update it?
Related
In my request data, if I have a duplication Guid ID, I want to generate a new Guid ID automatically. How to do it?
public class Roster { public Guid Id {get; set;} }
Here Guid Id is the primary key.
When I made an api post request, what would be the value I give for Guid Id?
If you use SQL and EntityFramework Core you could use this inside your model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid ActivityId { get; set; }
This will tell EF:
this property is the PRIMARY KEY of the table hence the [KEY]
this property should be automatically generated by the database
FYI you need to set a DEFAULT value for you SQL column like so:
(newsequentiaid()) tells SQL that he's in charge of creating a Globally Unique Id everytime you add a record to that table
Don't know if this is the answer you were looking for (nex time provide more info for us) anyway
hope this helps you Cheers!
UPDATE
I do not know if my solution works with MySQL i use it for SQL. Searching a bit online i found no resources to newsequentialid in MySQL database (but i could be wrong, do your own research if you'd like).
Anyway i just don't set it for example:
var activityDB = await context.Activity.FirstOrDefaultAsync(c => c.ActivityId == activity.ActivityId);
if (activityDB == null)
{
activityDB = new Activity();
context.Activity.Add(activityDB);
}
activityDB.Code = activity.Code;
activityDB.Description = activity.Description;
activityDB.Status = activity.Status;
Here's what the code does
check if my id exists if yes i have to edit if is null i don't
create new activity and edit
automatically EF nows what id to handle therefore no need to se it
If there is it means im editing for that id if not will create it automatically
This is my simple code for database insertion. But when am trying to insert to datetime column in the database, I got the error:
Conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
I tried some marked as answers here but none of those worked for me, I am using ASP.NET Core 5 MVC.
public void rfrPost()
{
nfmsdb.request_for_refund.Add(new request_for_refund
{
date_requested = date_requested
});
nfmsdb.SaveChanges();
}
My model in edmx:
public partial class request_for_refund
{
public DateTime date_requested { get; set; }
}
My column datatype in the database:
date_requested DateTime Nullable Yes
Thank you
I think this error occurs because the range of datetime and datetime2 is different. I think there is a detailed answer here.
Both the DATETIME and DATETIME2 map to System.DateTime in .NET - you cannot really do a "conversion", since it's really the same .NET type.
See the MSDN doc page:
http://msdn.microsoft.com/en-us/library/bb675168.aspx
There are two different values for the "SqlDbType" for these two - can
you specify those in your DataColumn definition?
BUT: on SQL Server, the date range supported is quite different.
DATETIME supports 1753/1/1 to "eternity" (9999/12/31), while DATETIME2
supports 0001/1/1 through eternity.
So what you really need to do is check for the year of the date - if
it's before 1753, you need to change it to something AFTER 1753 in
order for the DATETIME column in SQL Server to handle it.
im using c# with Entityframework to access to a Oracle database. After update the entities on the model, i'm just adding a new entity do a dbset, then i call dbcontext.SaveChanges(), and a exception is thrown "Input string was not in a correct format."
As Oracle does not have autonumbers, i've changed the "StoreGeneratedPattern" to Identity and the table where i'm tring to add a row have a relation to other table.
i'm missing something too basic?
some ideas?
myentity oNew = new myentity(){...}
ctx.myentity.Add(oNew);
ctx.SaveChanges();
I'm trying to store/save an image in an SQL Compact Edition (CE) database.
I declare the field in my Student model as:
[Column(TypeName = "image")]
public byte[] Photo { get; set; }
The database is created with the image data type for the Photo column as can be seen here:
The problem is:
When I run the app and try to save a Student with a Photo of 3 MB (for example), I get an exception:
validationError.ErrorMessage = "The field Photo must be a string or array type
with a maximum length of '4000'."
SQL Server CE supports these Data Types. In this comparison between SQL Express and SQL Compact Edition (CE) we have that SQL CE supports Binary (BLOB) storage through the use of image data type.
Image = Variable-length binary data
with a maximum length of 2^30–1
(1,073,741,823) bytes. Storage is the
length of the value in bytes.
Image should do the job I think.
What am I doing wrong here? Is this a bug?
Note:
I also tried the MaxLength data annotation:
[Column(TypeName = "image")]
[MaxLength(int.MaxValue)]
public byte[] Photo { get; set; }
but I get this exception:
Binary column with MaxLength greater than 8000 is not supported.
Edit:
I found the post about the release of EF 4.1. It has the following:
Change of default length for non-key
string and binary columns from ‘128’
to ‘Max’. SQL Compact does not support
‘Max’ columns, when running against
SQL Compact an additional Code First
convention will set a default length
of 4000. There are more details about
the change included in a recent blog
post (link below).
Well well well... the only way I could get it working was doing what is described here, that is, setting DbContext.Configuration.ValidateOnSaveEnabled = false. This is a workaround as the post suggests.
For those experiencing this problem, Erik Ejlskov Jensen posted a working console application which demonstrates the workaround to this bug. As the OP noted, a key part of the answer is:
public StudentContext()
{
// Required to prevent bug - http://stackoverflow.com/questions/5737733
this.Configuration.ValidateOnSaveEnabled = false;
}
A better solution has been found. Do not disable validation.
[Updates from blog post]
UPDATE: #DamienGuard, of LINQ to SQL and EF Code First fame, pointed out that a better and more provider agnostic solution is to use MaxLength rather than TypeName = “ntext”.
UPDATE 2: Using [MaxLength] prevents any validation errors, and disabling validation is not required.
The way to specify no maximum length using the MaxLength data annotation is to provide no maximum value. For example:
[MaxLength]
public byte[] Photo { get; set; }
The SQL Compact provider will then map the property to "image" and EF validation will recognize that there is no max length specified and so does not need to be disabled. If you want to be explicit about mapping to an "image" column then you can do this:
[Column(TypeName = "image")]
[MaxLength]
public byte[] Photo { get; set; }
which will produce the same result when using SQL Compact.
I know this is too late, but it could benefit other programmers.
You could add to the context class inside the OnModelCreating(DbModelBuilder modelBuilder) method
modelBuilder.Entity<EntityName>().Property(p => p.Photo).IsMaxLength();
I've been trying to insert row in the table having an identity column RequestID (which is primary key as well)
HelpdeskLog logEntry = new HelpdeskLog { RequestBody = message.Body };
if (attachment != null)
logEntry.Attachments = Helper.StreamToByteArray(attachment.ContentStream);
Database.HelpdeskLogs.InsertOnSubmit(logEntry);
But my code inevitably throws following error
Can't perform Create, Update or Delete operations on Table because it has no primary key.
despite primary key column exists indeed
That's what I tried to do:
To look in debugger the value of identity column being inserted in object model. It is 0
To insert manually (with SQL) fake values into table - works fine, identity values generated as expected
To assure if SQLMetal has generated table map correctly . All OK, primary key attribute is generated properly
Nevertheless, neither of approaches helped. What's the trick, does anybody know?
I've also had this problem come up in my C# code, and realized I'd forgotten the IsPrimaryKey designation:
[Table (Name = "MySessionEntries" )]
public class SessionEntry
{
[Column(IsPrimaryKey=true)] // <---- like this
public Guid SessionId { get; set; }
[Column]
public Guid UserId { get; set; }
[Column]
public DateTime Created { get; set; }
[Column]
public DateTime LastAccess { get; set; }
}
this is needed even if your database table (MySessionEntries, in this case) already has a primary key defined, since Linq doesn't automagically find that fact out unless you've used the linq2sql tools to pull your database definitions into visual studio.
LINQ does not allow to insert data into table without primary key. To achieve the insert data with table without primary key you can either use store procedure or create a query and execute using LINQ. Below link provide good explanation of the same.
Can't perform Create, Update or Delete operations on Table(Employee) because it has no primary key
Delete the table and then reinsert it. You must make sure there is a little small key next to the field before you do this. Recompile your project and all should be fine.
Just because you updated the dabase does not mean the DBML file somehow automatically updated. It does not, sorry.
As the the table has the primary key in SQL Server, re-addthe table in the linq2sql designer.
If that were not the case, you can configure which properties are part of the primary key by hand on the designer.