using Guid as PK with EF4 Code First - entity-framework-4

I have this class and table:
public class Foo
{
public Guid Id {get;set;}
public string Name {get;set;}
}
create table Foo
(
id uniqueidentifier primary KEY DEFAULT (newsequentialid()),
name nvarchar(255)
)
the problem is that when i try to save new foo the first one goes with the 0000-000-00 ... id and the second also, so I get constraint exception
anybody knows a fix ?

Have you set Identity StoreGeneratedPattern?
You can do it in the OnModelCreating method:
modelBuilder.Entity<Foo>().Property(o => o.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
or using the DataAnnotation attributes:
public class Foo {
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id {get;set;}
public string Name {get;set;}
}

Just building on Devart's Solution, I had this issue and using the
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
data annotation didn't work. The reason for this was i was using (as suggested in one of the code first tutorials) a SqlServerCompact database which doesn't support the Guid as identity. Just thought I'd post here in case anyone else had this issue. If you change the connection string so it is creating a SqlServer mdf instead of a Compact database it works perfectly.

Related

Set a Primary Key for an Entity without ingaffect database

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.

Integrate MVC Core Identity with other Database First Tables

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

Entity Framework Code First and Identity

I have a three layer project(DAL, Domain, MVC). I need to bound AuthorEntity from the DAL with ApplicationUser, which is in the MVC project.
They have a different context(EfContext, ApplicationDbContext).
First, I created a UserEntity and tried to implement IUser, which has string field Id (sting Id{get;}), I got an error:
"EntityType 'UserEntity' has no key defined.Define the key for this
EntityType"
I add attributes:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
It's not working. How to do this?
Primary Key property must be readable and writable.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id{get;set;}

What is the purpose of the [Key] attribute on a Primary Key in an asp.net MVC class?

I have read in various places, eg
http://techfunda.com/howto/132/primary-key-and-foreign-key-relationship-in-model
...that if you don't call the Id property in your model "Id" or "id" you need to add the annotation [Key], eg
[Key]
public int MyKey { get; set; }
...to it to tell the compiler it's the primary key in the database.
It seems like this may only be a requirement for Code First sites - although I can't find anything conclusive either way.
What is the purpose of [Key] and when should it be used?
Do I need to decorate any primary keys in models that are not called "Id" even when not building a Code First MVC site?
When you run code first and use this:
public class MyClass{
[Key]
public int MyKey { get; set; }
}
This will create in your database:
Table >> dbo.MyClass
Column >> MyKey IDENTITY NOT NULL
When you create a script to create the table, you need to make sure it is a primary key and it is used for code first approach
public class NewClass{
[key]
public int MyKey {get; set;}
}

Entity Framework Code First : One-To-One association using Annotations

I am having .NET MVC 5 and Identity...
I am trying to get a one to one relationship for my Member class to my MemberInfo class..
So, My classes looks something like this:
IdentityUser is in the Microsoft.AspNet.Identity.EntityFramework namespace with string Id as its ID.
public class GRNUser : IdentityUser {
....
....
}
public class MemberUser : GRNUser {
public virtual Member MemberInfo {get; set; }
}
public class Member {
public int ID {get; set; }
public string MemberUserID {get; set; }
public virtual MemberUser MemberUser { get; set; }
}
In my Context, I have this
modelBuilder.Entity<Member>().HasRequired(m => m.MemberUser)
.WithOptional(u => u.MemberInfo);
So, the MemberUser and Member should be able to navigate to and from each other using the MemberUser's ID property and Member's MemberUserID property.
However, when my Database is created, it has an additional column "MemberUser_Id" instead of using my MemberUserID that I specified. How do I make it use "MemberUserID" that I specified?
I've tried using a few combination so of the ForiegnKey Data Annotation, but keeps on getting this error:
Member_MemberUser_Source: : Multiplicity is not valid in Role 'Member_MemberUser_Source' in relationship 'Member_MemberUser'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
I don't know whether i understood you right or not, but i'l do my best to help.
(I'l assume that you work with code first migration)
If you want to make a one-to-one relation, why not try to make a standalone entity for your info which will have a foreign key for the user entity and that foreign key will be annotated as the primary key of the entity?
Another way is why just not add whatever attributes you like to the Application User entity and work with it?
In any case i might have misunderstood your purpose, so please feel free to explain further since your post is a bit confusing.

Resources