Autogenerate primary key (Guid) Entity Framework CTP5 - entity-framework

I have a following POCO class
public class Account
{
[Key,DatabaseGenerated(DatabaseGenerationOption.Identity)]
public string AccountId { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public string Email { set; get; }
}
I get the following exception when the database gets created
Identity column 'AccountId' must be of data type int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable.

Shouldn't you have:
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid AccountId { set; get; }
?

Jeff's answer is right. Just a little tip for you. Using EF6 I wrote next configuration in order to set all fields with name "Id" and type "Guid" as identity.
modelBuilder.Properties<Guid>()
.Where(info => info.Name.ToLower()== "id")
.Configure(configuration => configuration.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
So I don't have to write [DatabaseGenerated(DatabaseGenerationOption.Identity)] everytime.

Sound like you have to update your AccountId property from string to one of the mentioned datatypes in the exception:
int, bigint, smallint, tinyint, or decimal or numeric with a scale of 0, and constrained to be nonnullable
Any reason why it's now a string?

Related

Ef core and multiple parent entities use list of the same child entity?

Is there an easy way to have a setup like this in EF Core?
ProjectEntity
Id
Name
List<Notes>
CustomerEntity
Id
Name
List<Notes>
NotesEntity
Id
Date
Note
Every parent entity would have a one-to-many relation to same child entity. So I can not use normal behavior as
NotesEntity
Id
ParentId
Date
Note
I have some idea to have like above but also add one field that said what the parent entity is, is that the right way to do it or is there a better way? If I use this way I can't use EF Core normal behavior with one-to-many relationship? I need to make more manual work for search / add and so on?
Edit :
Entity Framework multiple parent tables I found this solution, but there I need to make a connection from my child to every parent I use, it could be alot of them.
Did also find a solution like :
BaseEntity
List<Notes>
ProjectEntity:BaseEntity
NotesEntity
Id
BaseEntityId
...
This last solution maybe is the best way to do it if I have alot of parent entities?
[EDIT 220922]
Could [Owned] type has collection of other Items? Or this feature won't work on owned entitys? I guess this behavior isn't supported?
[Owned]
public class Note
{
public int Id { get; set; }
public string Text { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public ICollection<string> Tags { get; set; }
}
I got an error on ICollection-row when I try to add-migration.
Unabel to determine the relationshop represented by navigation ... of
typ 'ICollection' Either manually configure the relationship, or
ignore this property using the '[NotMapped]' attribute.....
Maybe I could have one middleentity like :
public class NoteTagsEntity
{
public int Id { get; set; }
public ICollection<string> Tags { get; set; }
}
And then :
[Owned]
public class Note
{
public int Id { get; set; }
public string Text { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public int NoteTagsId { get; set; }
public NoteTagsId NoteTagsId { get; set; }
}
Edit
I solved the Note functionality with having more FK's, one that point to Id of parent and one FK Id that point to what module that use that particular note. Here I don't have parent - child relation in my entities, I need to do this connection by myself but in this way it's easy to apply more modules that use note's later.
Use Owned Entity Types, and each entity will get its own notes table.
eg
public abstract class Entity
{
public int Id { get; set; }
}
public abstract class EntityWithNotes: Entity
{
public virtual ICollection<Note> Notes { get; set; }
}
[Owned]
public class Note
{
public int Id { get; set; }
public string Text { get; set; }
}
public class Project : EntityWithNotes
{
public string Name { get; set; }
}
public class Customer : EntityWithNotes
{
public string Name { get; set; }
}
creates
CREATE TABLE [Customer_Notes] (
[Id] int NOT NULL IDENTITY,
[CustomerId] int NOT NULL,
[Text] nvarchar(max) NOT NULL,
CONSTRAINT [PK_Customer_Notes] PRIMARY KEY ([CustomerId], [Id]),
CONSTRAINT [FK_Customer_Notes_Customer_CustomerId] FOREIGN KEY ([CustomerId]) REFERENCES [Customer] ([Id]) ON DELETE CASCADE
);
CREATE TABLE [Project_Notes] (
[Id] int NOT NULL IDENTITY,
[ProjectId] int NOT NULL,
[Text] nvarchar(max) NOT NULL,
CONSTRAINT [PK_Project_Notes] PRIMARY KEY ([ProjectId], [Id]),
CONSTRAINT [FK_Project_Notes_Project_ProjectId] FOREIGN KEY ([ProjectId]) REFERENCES [Project] ([Id]) ON DELETE CASCADE
);

Entity Framework 6: map complex type to multiple columns

I have a problem with Entity Framework (6, not Core). I already tried several things and googled around but I can't figure it out so I'm asking here.
Thats my db-scheme:
CREATE TABLE MyItem
(
[Id] int IDENTITY(1,1) NOT NULL,
[Name] varchar(100) NOT NULL,
[Start] date NOT NULL,
[End] date NOT NULL
)
And these are my classes:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
public MyTimespan IsValidTimespan { get; set; }
}
public class MyTimespan
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
I want to map
the value from "MyItem.IsValidTimespan.Start" to the "Start"-column
the value from "MyItem.IsValidTimespan.Ende" to the "Ende"-column
I already tried different things with Attributes on the MyTimespan-class ("ComplexType" and "Column" Attributes) and also some hacks with the modelBuilder, nothing worked.
How can I get this to work?
Thank you and best regards,
Alex
Ok I got it. The code I posted above is not 100% correct: the properties of MyTimespan did not had setters. The following changes in "MyTimespan" did it:
adding the annotations mentioned in my question
adding private setters to the properties
adding a private default constructor

Entity Framework 5 CodeFirst - "Column names in each table must be unique."

I'm creating the following table on PostgreSQL:
create table dbo.user_ratings (
user_id int not null,
user_rated_id int not null,
value decimal not null,
status_id int not null,
created_at timestamp with time zone not null,
updated_at timestamp with time zone null,
user_comment text null,
primary key (user_id, user_rated_id),
foreign key (user_id) references dbo.users(id),
foreign key (status_id) references dbo.status(id),
foreign key (user_rated_id) references dbo.users(id));
When mapping the table using CodeFirst, I'm doing the following:
[Table("user_ratings", Schema="dbo")]
public class UserRating {
[Key, Column("user_id", Order = 0)]
public int UserId { get; set; }
public virtual User User { get; set; }
[Key, Column("user_rated_id", Order = 1)]
public int UserRatedId { get; set; }
public virtual User UserRated { get; set; }
[Column("status_id")]
public int StatusId { get; set; }
public virtual Status Status { get; set; }
public decimal Value { get; set; }
[Column("user_comment")]
public string UserComment { get; set; }
[Column("created_at")]
public DateTime CreatedAt { get; set; }
[Column("updated_at")]
public DateTime UpdatedAt { get; set; }
}
Well, so far, so good. When I try to query something, I'm getting the error below:
Column names in each table must be unique. Column name 'User_Id' in table 'user_ratings' is specified more than once.
What is wrong with this? When I remove the mapping related to the column user_id, it's passing, but it's not right. Can someone help me?
Thank you all!!!
Seems that this error is related only to SQLServer databases. I still had some SQLServer configurations on my Web.config/App.config, that's why this error was appearing. Without SQLServer configurations, the error is gone.

Getting POCO mapping error in Entity Framework

I feel like I'm missing some basic setup step here, but I've been wading through forum posts, blog articles, and videos for hours and keep having the same problem, so I figure it's time to post.
The error I'm getting is:
Mapping and metadata information could not be found for EntityType 'qTrade.BusinessLayer.Domain.Model.Audit.LoanPool'.
I've got an Entity Model file called Audit.edmx that has code generation turned off. In there I generated an Entity from the database for this table (pasted from the create script, LoanPoolAuditId is the Primary Key):
CREATE TABLE [Audit].[LoanPool](
[Type] [char](1) NULL,
[TableName] [varchar](128) NULL,
[PK] [varchar](1000) NULL,
[FieldName] [varchar](128) NULL,
[OldValue] [varchar](1000) NULL,
[NewValue] [varchar](1000) NULL,
[UpdateDate] [datetime] NULL,
[UserName] [varchar](128) NULL,
[CommonID] [int] NULL,
[LoanPoolAuditId] [int] IDENTITY(1,1) NOT NULL,
I've got a class I created to be a POCO elsewhere in the same project
public class LoanPool
{
public int CommonID { get; set; }
public string FieldName { get; set; }
public int LoanPoolAuditId { get; set; }
public string NewValue { get; set; }
public string OldValue { get; set; }
public string PK { get; set; }
public string TableName { get; set; }
public char Type { get; set; }
public DateTime UpdateDate { get; set; }
public string UserName { get; set; }
}
And I've got the context class
public class AuditContext : ObjectContext
{
public AuditContext()
: base("name=AuditEntities", "AuditEntities")
{
this.LoanPools = CreateObjectSet<LoanPool>();
}
public ObjectSet<LoanPool> LoanPools { get; set; }
}
Heres the connection string for reference
"metadata=res://*/EntityModels.Audit.csdl|res://*/EntityModels.Audit.ssdl|res://*/EntityModels.Audit.msl;provider=System.Data.SqlClient;provider connection string="data source=serverName;initial catalog=databaseName;persist security info=True;user id=*SNIP*;password=*SNIP*;multipleactiveresultsets=True;App=EntityFramework""
Very simple (or so I thought).
When I go to instantiate an instance of the context I get the aforementioned error on the CreateObjectSet step.
Any suggestions would be greatly appreciated, even if they are simple or obvious, this is my first time using POCOs so there's a good chance I missed something.
Go figure I had no trouble using code-first in a different project :-P
Thanks
We generally recommend using DbContext as the primary means of operating with anything EF 4.1 or beyond. In this case you would need to get rid of your existing .edmx and modify your AuditContext as follows:
public class AuditContext : DbContext
{
public DbSet<LoanPool> LoanPools { get; set; }
}
You can also see the corresponding walkthrough on the official blog here: http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-code-first-walkthrough.aspx. Also, you will need to put the [Key] attribute on LoanPoolAuditId as it does not conform to the expected conventions. That's also mentioned in the blog post.
HTH,
Mark

Entity framework code-first null foreign key

I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).
How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.
The model is as follows:
public class User{
public int CountryId { get; set; }
public Country Country { get; set; }
}
public class Country{
public List<User> Users {get; set;}
public int CountryId {get; set;}
}
Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}
You must make your foreign key nullable:
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
public virtual Country Country { get; set; }
}
I prefer this (below):
public class User
{
public int Id { get; set; }
public int? CountryId { get; set; }
[ForeignKey("CountryId")]
public virtual Country Country { get; set; }
}
Because EF was creating 2 foreign keys in the database table: CountryId, and CountryId1, but the code above fixed that.
I have the same problem now ,
I have foreign key and i need put it as nullable,
to solve this problem you should put
modelBuilder.Entity<Country>()
.HasMany(c => c.Users)
.WithOptional(c => c.Country)
.HasForeignKey(c => c.CountryId)
.WillCascadeOnDelete(false);
in DBContext class
I am sorry for answer you very late :)
I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.
Guide link below:
https://learn.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN