Entity Framework 4 & Code First CTP 5 - Missing Key - entity-framework

Can someone make sense of this error?
One or more validation errors were detected during model generation:
System.Data.Edm.EdmEntityType: : EntityType 'Address' has no key defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: The EntitySet Addresses is based on type Address that has no keys defined.
I have this entity defined:
public class Address
{
[Key]
public int ID;
[Required]
[MinLength(1)]
[MaxLength(200)]
public string Address1 { get; set; }
[MinLength(1)]
[MaxLength(200)]
public string Address2 { get; set; }
[Required]
[MinLength(1)]
[MaxLength(10)]
public string Zip { get; set; }
[MinLength(1)]
[MaxLength(100)]
public string Province { get; set; }
public virtual US_State State { get; set; }
[Required]
public virtual Country Country { get; set; }
}
My question is: how does the error make any sense for a class that both has a Key attribute data annotation as well as the conventional ID name for its PK.
I would think this class satisfies all rules needed for a meaningful entity to be generated from it.

Like Craig mentioned, making ID a property will solve your problem.
public int ID { get; set; }
Besides, you don't need the [Key] attribute on ID, it will be recognized as object identifier (i.e. Primary Key) by code first based on conventions.

Related

Entity Frameworks Creates Auto Column

I am having a problem in Entity Framework. Entity Framework is generating auto column in sql-server and I am not geting how to make insert operation in that particuler column.
For Example in Teacher class,
public class Teacher
{
[Key]
public String Email { set; get; }
public String Name { set; get; }
public List<TeacherBasicInformation> Teacher_Basic_Information { set; get; } = new List<TeacherBasicInformation>();
public String Password { set; get; }
public List<Course> course { set; get; } = new List<Course>();
[JsonIgnore]
public String JWT_Token { set; get; }
[NotMapped]
[Compare("Password")]
public String ConfrimPassword { set; get; }
}
And in TeacherBasicInformation class ,
public class TeacherBasicInformation
{
[Key]
public int ID { set; get; }
[Required]
[MaxLength(20)]
public String Phone { set; get; }
[Required]
[MaxLength(100)]
public String Address { set; get; }
}
After the migration in the sql server, in TeacherBasicInformation table a auto column is created named 'TeacherEmail'. How Can I insert data into this column using form in asp.net core.
In order to prevent auto-generated columns for FK, use [ForeignKey("YourForeignKey")] on the related table in the entity class:
public int TeacherId { get; set; }
[ForeignKey("TeacherId")]
public virtual Teacher Teacher { get; set; }
It looks like you have the email column set up as the primary key column in your Teacher class, and the related database column. If that's the case, you're going to have trouble with it as it will need to be unique to that record, and primary keys aren't designed to be changed. It can be done in certain scenarios but isn't a best practice.
Perhaps a better approach is to have the [Key] attribute on a property of public int Id { get; set; } so they primary key is now a discrete number instead of an email address. Then you can access, set, and update the email address on each record, without interfering with the key at all.

Entity framework code first cant create primary and foreign key relationship

I am trying to create a relationship between two tables but keep getting the following error:
The ForeignKeyAttribute on property 'CallLogId' on type
'Ylp.Web.ParkingApi.DataLayer.Entities.ApiCallLogDetailEntity' is not
valid. The navigation property 'ApiCallLog' was not found on the
dependent type
'Ylp.Web.ParkingApi.DataLayer.Entities.ApiCallLogDetailEntity'. The
Name value should be a valid navigation property name.
DbContextMapping:
modelBuilder.Entity<ApiCallLogDetailEntity>()
.HasRequired<ApiCallLogEntity>(p => p.ApiCallLog);
Primary table:
[Table("ApiCallLog")]
public class ApiCallLogEntity
{
[Key, Column(Order = 0)]
public string CallLogId { get; set; }
[Key, Column(Order = 1)]
public string UserId { get; set; }
[Required]
public string CallFilterId { get; set; }
[Required]
public DateTime LastUpdated { get; set; }
[Required]
public int Count { get; set; }
public virtual ICollection<ApiCallLogDetailEntity> Details { get; set; }
}
foreign table:
[Table("ApiCallLogDetail")]
public class ApiCallLogDetailEntity
{
[ForeignKey("ApiCallLog")]
public string CallLogId { get; set; }
[Required]
public string PrametersHashCode { get; set; }
[Required]
public DateTime LastUpdated { get; set; }
public ApiCallLogEntity ApiCallLog { get;}
}
The foreign key must refer to the whole primary key of the parent table. In your parent table you have a composite primary key which includes CallLogId and UserId. The message is confusing, but this can be part of the error. Is it really necessary to include the UserId in the PK?
Another error is that you have not defined the PK in the dependent table. If the UserId is also necessary on the PK, include it in the dependent table, and make it part of the FK.

Foreign Key Relationships with Entity Framework Code First (EntityData Issue)

I have two entity models, an Account and User and I am having difficulties implement foreign keys in the dependant model (User). As I am developing an Azure Mobile Service app I need to use the Entity Data interface which provides an 'Id' key field by default.
public class Account : EntityData
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AccountId { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string EmailAddress { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string SecurityQuestion { get; set; }
[Required]
public string SecurityAnswer { get; set; }
[Required]
public bool IsBusiness { get; set; }
public virtual User User { get; set; }
public virtual Business Business { get; set; }
}
public class User : EntityData
{
[Key, Column(Order=1)]
public virtual string Id { get; set; }
[Key, Column(Order=2), ForeignKey("Account")]
public int AccountId { get; set; }
public int UserId { get; set; }
[Required]
public string Forename { get; set; }
[Required]
public string Surname { get; set; }
public virtual Account Account { get; set; }
}
My issue occurs when I specify I want to find 'AccountId' Entity Framework interprets it as 'Account' table, 'Id' column.
Output from Code Migrations:-
User_Account_Source: : Multiplicity is not valid in Role
'User_Account_Source' in relationship 'User_Account'. Because the
Dependent Role properties are not the key properties, the upper bound
of the multiplicity of the Dependent Role must be '*'.
User_Account_Target_User_Account_Source: : The types of all properties
in the Dependent Role of a referential constraint must be the same as
the corresponding property types in the Principal Role. The type of
property 'AccountId' on entity 'User' does not match the type of
property 'Id' on entity 'Account' in the referential constraint
'User_Account'.
Any insight would be highly appreciated!
The reason why EF understands it is one-to-many relationship instead one-to-one is because you are composing your PKs with the Id property, wich is not a FK.In one-to-one relationships one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal. When configuring one-to-one relationships, Entity Framework requires that the primary key of the dependent also be the foreign key, otherwise EF doesn't see it as one-to-one relation.
public class Account
{
[Key]
public int Id { get; set; }
public virtual User User{ get; set; }
}
public class User
{
[Key, ForeignKey("Account")]
public int AccountId { get; set; }
public virtual Account Account{ get; set; }
}
If you think about that, it makes sense,otherwise, the below records could happen:
Accounts
Id
11111111
22222222
Users
Id AccountId
12rr 11111111
22tt 11111111

Entity Framework: Code First - Column Mapping

I have a model like this:
public class Entity
{
[Key, Required]
public virtual long EntityId { get; set; }
[Required]
public virtual string Name { get; set; }
public virtual long? ParentEntityId { get; set; }
}
and this is my table:
create table Entities(
EntityId bigint not null identity(1, 1),
Name nvarchar(64) not null,
ParentEntityId bigint null
)
ParentEntityId is a foreign key to EntityId.
When I try to create a Entity entity this is the exception I get:
Invalid column name 'ParentEntity_EntityId'.
I don't know why EF is picking that convention for that particular column, but if I do this:
[Column("TryPickThisName")]
public virtual int? ParentEntityId { get; set; }
The same error shows up with "TryPickThisName" column name. And finally if I write the column name correctly or remove the attribute it will show the original error message.
Did you leave part of your model out?
I think what is happening is you're wanting to create a self referencing table, with Entity optionally referring to itself if it has a ParentEntity.
What's happening is EF is creating the ParentEntity_EntityId because you didn't explicitly map the FK property to the navigation property. Adding a ForeignKey data annotation will correct this.
public class Entity
{
[Key, Required]
public virtual long EntityId { get; set; }
[Required]
public virtual string Name { get; set; }
[ForeignKey("ParentEntity")]
public virtual long? ParentEntityId { get; set; }
public virtual Entity ParentEntity { get; set; }
}
Creates this database:

One to One Relationship on Primary Key with Entity Framework Code First

I'm currently getting the following error when trying to create an one to one relationship using Code First:
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'C001_Holding_Teste_C001_Holding_Source' in relationship 'C001_Holding_Teste_C001_Holding'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be 1.
My entity definitions are the following:
[Table("C001_Holding", Schema = "Cad")]
public partial class C001_Holding
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int C001_Id { get; set; }
[MaxLength(16)]
public string C001_Codigo { get; set; }
[MaxLength(100)]
public string C001_Descricao { get; set; }
}
public class C001_Holding_Test
{
[Key]
public int C001_Id { get; set; }
[MaxLength(100)]
public string C001_TestInfo { get; set; }
[ForeignKey("C001_Id")]
public virtual C001_Holding C001_Holding { get; set; }
}
I didn't want to use Fluent to create these relationships, does anyone knows why this is happening?
Tks.
It is possible to place the ForeignKey attribute either on a navigation property and then specify the name of the property you want to have as the foreign key (that's what you did). Or you can place it on the foreign key property and then specify the name of the navigation property which represents the relationship. This would look like:
public class C001_Holding_Test
{
[Key]
[ForeignKey("C001_Holding")]
public int C001_Id { get; set; }
[MaxLength(100)]
public string C001_TestInfo { get; set; }
public virtual C001_Holding C001_Holding { get; set; }
}
For some reason this second option works while the first throws an error. (It feels like a bug to me because both options should represent the same relationship. Or there is actually a semantic difference which I don't see...)