In my asp.net mvc4 sample i have table in the name of Sample with three column as Name,Dept and Id.In this Id as identity and primary.I get a value for Name and Dept from user and insert that value to Sample table of entity framework.It pass value '0' to Id.And i got an error as "Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries".Please help me.
set "autoincrement" on the column and set the id as primary key in sql server ..
In EF code-first this is done by data annotations. Make sure you recreate your table (or database) after changing the scheme.
public class Sample
{
[Key]
[Required]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //auto increment id
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Dept { get; set; }
}
You don't need to pass an integer for Id. EF will resolve this automatically. Just create the object by filling in the name and the dept. By saving the changes to the database, EF will automatically fill in the auto generated Id.
Related
I'm working on an ASP.NET MVC project, I use Entity Framework (Database First), I created a data model depend on SQL server database, I created a Table in the database and I updated the data model from the database, and when I try to add a record to the new table I created (this table doesn't have a PK) I got an error, when I search about the error I Understood that in Entity Framework need to have a PK for Entity.
So I ASK if I can set a Primary Key for an Entity without affect database, or any other solution to solve this problem.
You can use partial Class for set Key and without effect Original Model and Database
// orginal class **Entity** `YourEntity.cs`
public class YourEntity
{
public int Id { get; set; }
}
Then create a new Class must name different ordinal class ex YourEntityMeta.cs it is physical name
// must change name ordinal class `YourEntity.cs` but add **partial** keyword
[MetadataType(typeof(Metadata))]
public partial class YourEntity
{
sealed class Metadata
{
[Key]
public int Id { get; set; }
}
}
Entity Framework always needs a primary key column with name id. Add a column (id) in the database table and set "Is Identity: true" for it. Then update the database model of your project.
I'm upgrading from EF Core 2.2 to EF Core 3.1. I have an entity Patient with a GUID Id:
class Patient {
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
A DbSet is defined for this type:
public DbSet<Patient> Patients { get; set; }
In EF 2.2, when I added a new Patient, the Id would be automatically generated when the object was added to the DbSet:
// newPatient.Id -> 00000000-0000-0000-0000-000000000000
ctx.Patients.Add(newPatient);
// newPatient.Id -> C1D5ACB8-A4C9-4680-AF2F-BF5E5B0AC1B6 <=== GUID generated
Now, in EF 3.1, the Id is not being automatically generated upon Add:
// newPatient.Id -> 00000000-0000-0000-0000-000000000000
ctx.Patients.Add(newPatient);
// newPatient.Id -> 00000000-0000-0000-0000-000000000000 <=== still an empty GUID
This obviously breaks my code.
In EF Core 3.0 there is a breaking change "String and byte array keys are not client-generated by default". However, this breaking change indicates string and byte array keys, not GUID keys. Also, I have tried the recommended mitigations with FluentAPI and Data Annotations and it does not resolve my issue (still no GUID generated).
I am using the dotConnect for Oracle database provider v9.11. I did not find any breaking changes there that would affect this.
Of course I can explicitly assign a GUID Id in my code, but I'd like to make this work as it did before in EF Core 2.2.
Any suggestions why this is not working? Thanks.
I am using MVC Core with the default individual user authentication.
I added FullName field to AspNetUsers Table and it is working fine.
I need to create a relationship between my tables to the id field in the AspNetUsers table so I can get the fullname of the user.
I have no idea on how to create relationship in Entity framework, I tried to add the following in the ApplicationUser Class
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public mytable T { get; set; }
}
and
in mytable model, I added the following
public virtual ICollection<ApplicationUser> ApplicationUser { get; set; }
unfortunately, I am getting the following error:
The entity type 'IdentityUserLogin' requires a primary key to be defined
any idea?
The first issue solved by following link
https://forums.asp.net/post/6144294.aspx
the IdentityUserLogin' requires a primary key to be defined also solved by
https://stackoverflow.com/a/40824620/7046796
As of Identity 2 they have switched from a id with an integer value (ex. 1,2,3,4,...) to a id with a nvarchar value that stores the id as some long string like
a234vt-23sdlj23klj-34jkh34jh34-23jk4jh2
If I'm creating an object that will have a single owner belonging to the person logged in, so I need to attach the user id to it, should I use this new id from Identity 2 or should I try and create some other value like an integer and put it into the aspnetusers table? Does it really matter, all I'm doing is fetching Gift object by owner(userid) and displaying/modifying gift objects on a form.
here is an example of my product object
public class Gift
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Category> Categories { get; set; }
public int Rating { get; set; }
public GiftStatus Status { get; set; }
Public string UserId {get; set; //where userid is the id of the user that owns this object, should it be 3kj23jh3-h3hk1jh2-khj2h34l1b-n22g35l ???
}
There is no problem with using the Guid UserId to reference a user, if that's what you're concerned about. Unless you have a specific reason for not wanting to use a Guid as the UserId, I would suggest you just use the default behavior in order to simplify implementation. Having two separate Ids to keep track of a user sounds needlessly complicated, I wouldn't recommend that path.
If you do have a good reason for requiring an Int as the primary key instead of a Guid, you might take a look at this: http://blogs.msdn.com/b/webdev/archive/2014/03/20/test-announcing-rtm-of-asp-net-identity-2-0-0.aspx (scroll down to the "Make the type of Primary Key be extensible for Users and Roles" section). This page has a link to an example project which shows you how to use an Int as the PK. It also mentions that this extension can be used to migrate applications which use Int PKs to the new Identity 2.0.
Here's another article that may be helpful: http://www.codeproject.com/Articles/777733/ASP-NET-Identity-Change-Primary-Key
Is is possible, to get the new value of RowVersion using the same DbContext, without reloading the entity from the database?
Scenario:
Load data into editor form
Save new values
The row in the table gets updated, new value of RowVersion is generated
However, the saved entity still holds the old value of RowVersion, so the new value can not be passed back to the client
All concurrency control articles are usually concerned only with preventing the update (e.g. see this).
However, in the example from the article, a successful update is followed by a redirect to page, where the saved entity is read again and now it has a new RowVersion value. I would like to avoid this redirect.
Thanks to grennis, I found out the source of my problems.
I defined the interface and an entity like
public interface IRowVersion
{
// Attention: this will not be "inherited" by the implementing class !!!
[Timestamp]
byte[] VersionStamp { get; set; }
}
public class Directory : IRowVersion
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
// If this attribute is missing here, then row version is used
// My initial version was without this attribute
[Timestamp]
public byte[] VersionStamp { get; set; }
}
In my problematic version, I thought that having the attribute on the interface property is enough. However, the attribute must be explicitly applied on the entity's property. Otherwise it will not be used at all (not even as the part of update SQL statement). The value was updated only because the DB updates the column value automatically and of course, at next read, I got the new value.
Not entirely related to the problem, but still worth mentioning... The following is really a killer feature of EF6
ctx.Database.Log = s => Debug.Write(s);
SQL Profiler, it was nice knowing you :-)