I have a problem with a navigation property not being loaded. I have this same setup with all my other entities, but this is using a property that isnt a natural FK (Number) and wont cascade, that will be handled by a trigger.
Expression<Func<DivisionBracketGameParticipant, object>>[] includes2 = {
q => q.DivisionWinnerBracketGame,
q => q.DivisionLoserBracketGame
};
var test = _divisionBracketGameParticipantsRepository.GetMany(includes2,
q =>
q.DivisionBracketGame.DivisionBracket.Division.
EventId == eventId);
Database Schema
DivisionBracketGame
Id
Number
DivisionBracketGameParticipant
Id
DivisionBracketGameId -> Id
DivisionBracketGameWinnerNumber -> Number
DivisionBracketGameLoserNumber -> Number
Entities
[Table("DivisionBracketGame", Schema = "GrassrootsHoops")]
public class DivisionBracketGame : BaseEntity
{
public int Id{ get; set; }
public int Number { get; set; }
[InverseProperty("DivisionBracketGame")]
public virtual ICollection<DivisionBracketGameParticipant> DivisionBracketGameParticipants { get; set; }
[InverseProperty("DivisionWinnerBracketGame")]
public virtual ICollection<DivisionBracketGameParticipant> DivisionWinnerBracketGameParticipants { get; set; }
[InverseProperty("DivisionLoserBracketGame")]
public virtual ICollection<DivisionBracketGameParticipant> DivisionLoserBracketGameParticipants { get; set; }
}
[Table("DivisionBracketGameParticipant", Schema = "GrassrootsHoops")]
public class DivisionBracketGameParticipant : BaseEntity
{
public int Id{ get; set; }
public virtual int DivisionBracketGameId { get; set; }
public virtual int? DivisionWinnerBracketGameNumber { get; set; }
public virtual int? DivisionLoserBracketGameNumber { get; set; }
[ForeignKey("DivisionBracketGameId")]
public virtual DivisionBracketGame DivisionBracketGame { get; set; }
[ForeignKey("DivisionWinnerBracketGameNumber")]
public virtual DivisionBracketGame DivisionWinnerBracketGame { get; set; }
[ForeignKey("DivisionLoserBracketGameNumber")]
public virtual DivisionBracketGame DivisionLoserBracketGame { get; set; }
}
EF will not create relation to Number because it is not a primary key. Primary key is of your DivisionBracketGame is Id so both DivisionWinnerBracketGame and DivisionLoserBracketGame are targeting Id (not Number).
One-to-many relation demands that column in principal table is unique - in your case the column should be a Number. This is possible in database by either using primary key from principal table or by using unique index on that column. EF doesn't support unique indexes / candidate keys so the only way to build one-to-many relation in EF is through primary key of principal table.
The FK value is used to get related value so at the moment it probably looks for records with wrong value because it uses a wrong column.
Related
I have a model class:
public class UserProfile
{
public string UserID { get; set; }
public string Name{ get; set; }
public ICollection<AddressMaster> AddressMaster { get; set; }
}
The above class have a 1 to many relationship with AddressMaster model class given below:
public class AddressMaster
{
public string AddrID{ get; set; }
public string AddressLine1{ get; set; }
public UserProfile UserProfile { get; set; }
public TheatreLocation TheatreLocation { get; set; }
}
The problem is, there is one other model also that has a 1 to many relationship with addressmaster, which is:
public class TheatreLocation
{
public string LocationID { get; set; }
public string Name{ get; set; }
public ICollection<AddressMaster> AddressMaster { get; set; }
}
So instead of having foreign key at the addressmaster, how can we have a intermediate table between addressmaster and the userprofile & another such table b/w addressmaster and theatre?
Or am i getting the whole concept wrong?
Thanks.
So instead of having foreign key at the addressmaster, how can we have
a intermediate table between addressmaster and the userprofile &
another such table b/w addressmaster and theatre?
If you do not want to set any foreign key and add a intermediate table.Design like below:
public class UserProfile
{
[Key]
public string UserID { get; set; }
public string Name { get; set; }
}
public class AddressMaster
{
[Key]
public string AddrID { get; set; }
public string AddressLine1 { get; set; }
}
public class UserAddress
{
[Key]
public string AddrID { get; set; }
public string UserID { get; set; }
}
Add the primary key to the intermediate table UserAddress.The AddrId could only has one value,but the UserID could have many value which is like one-to-many relationship.
Or am i getting the whole concept wrong?
Nothing wrong.Using navigation property like what you did is also good.
Your table definitions would probably wind up something like this:
UserProfile
UserId PK
Theather
TheatreId PK
Address
AddrID PK
AddressLine1
UserAddress
UserId PK & FK
AddressId FK
TheatreAddress
TheatreID PK & FK
AddressId FK
This is just good normalisation - i.e. you have a generic 'address' table in the database. Several entities may have an address and have either one-many or many-many relationships with addresses, but a specific address only needs to be recorded once.
The PK on the intermediate table only on the UserId (for example) ensures that this is one-many and not many-many.
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.
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.
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; }
Is it possible to map an Entity with one identity index that auto increments and a foreign key linking it to another table?
public class Item
{
public int ItemID { get; set; }
[StringLength(20)]
public string Barcode { get; set; }
[StringLength(50)]
public string Name { get; set; }
[StringLength(50)]
public string Description { get; set; }
public decimal Price { get; set; }
[ForeignKey("ItemCategory")]
public string CatID { get; set; }
public virtual ItemCategory ItemCategory { get; set; }
}
public class ItemCategory
{
// This should be the identity index
public int ItemCategoryID { get; set; }
// This should be the foreign key
public string CatID { get; set; }
public string Name { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
I saw this answer - should I configure my tables with modelbuilder?
Foreign key in Item must point to primary key in ItemCategory. FKs in EF behave in exactly same way as in databases. It means that FK must point to property with unique values in the principal entity. The problem is that EF doesn't support unique index / constraint so the only way to achieve uniqueness is primary key.
Because of that you cannot point your FK to CatID unless it is part of primary key but in such case you will have composite key containing both ItemCategoryID and CatID and your Item class will have to contain both of them to form correct FK.