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

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

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.

EF 4.1 code first with one-to-many relationship creates duplicate foreign keys

I am using entity framework code first. I have 2 entities (Users and Profile) and the relationship between them is one-to-many, that is, one user can only have one profile, but one profile can be assigned to many users. Below the entities:
[Table("Users")]
public class User
{
[Key(), Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public virtual string Name { get; set; }
[Required]
[ForeignKey("Profile")]
public virtual int ProfileId { get; set; }
public virtual Profile Profile { get; set; }
public virtual ICollection<AnotherEntityB> anotherEntityB { get; set; }
}
[Table("Profiles")]
public class Profile
{
[Key(), Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public virtual string Name { get; set; }
// Below the user that performs the discharge of the profile. Only 1 user can do it.
[ForeignKey("User")]
public virtual int? UserId { get; set; }
public virtual User User { get; set; }
public virtual DateTime? dischargeDate { get; set; } <-- this is the date that user performs the discharge of the profile
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<AnotherEntityC> anotherEntityC { get; set; }
}
also I have removed some conventions in the OnModelCreating method:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
The problem is that EF is creating two foreign keys in user entity:
ProfileId (FK, int, No NULL)
Profile_Id (FK, int, NULL)
and only one foreign key should be in Users entity:
ProfileId (FK, int, No NULL)
What's wrong?
Because there are two navigation properties User and Users in Profile that refer to the User entity EF cannot decide by a convention which of the two belongs to the inverse property Profile in entity User. You must EF give a hint using the [InverseProperty] attribute:
[InverseProperty("Users")]
public virtual Profile Profile { get; set; }
Now, it defines that User.Profile is the inverse navigation property of Profile.Users and that both are ends of the same relationship. Without the attribute EF assumes that the two navigation properties are ends of two different relationships and one of them is responsible for the additional foreign key Profile_Id.
Here is a bit more background.

Entity Framework CF Fluent API mapping

I have 2 entities:
public class User
{
public int userId { get; set; }
public string name { get; set; }
public Guid userGuid { get; set; }
}
public class Absence
{
public int absenceId { get; set; }
public Guid applicantId { get; set; }
public User applicant { get; set; }
public Guid permitterId{ get; set; }
public User permitter{ get; set; }
...
}
AbsencesConfiguration:
this.HasRequired(u => u.Applicant).WithMany().HasForeignKey(d => d.ApplicantId);
this.HasRequired(u => u.Permitter).WithMany().HasForeignKey(d => d.PermitterId);
I'd like a Fluent API mapping between the two classes, but it gives this error message:
Blockquote\tSystem.Data.Entity.Edm.EdmAssociationConstraint: : 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 'ApplicantId' on entity 'Absences' does not match the type of property 'UserId' on entity 'User' in the referential constraint 'Absences_Applicant'.
I think this is because EF try to join the two tables with the UserId of the User entity and not with UserGuid column. I thought I would make these two columns of Absence entity unique, but how I can map them together?
Thanks in advance.
The problem is your User primary key is an int, but your foreign key is a Guid.
You need to alter either your User class to have a guid for userId:
public Guid userId { get; set; }
or, update your Absence class to use an int:
public int applicantId { get; set; }

Entity Framework 4 & Code First CTP 5 - Missing Key

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.