I am trying to link two models with One to One relationship
the classes are following:
public class Customer : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[ForeignKey("Account")]
public int AccountId { get; set; }
public virtual Account Account { get; set; }
[Required(AllowEmptyStrings = false)]
public string Address { get; set; }
[Required(AllowEmptyStrings = false)]
public string PublicName { get; set; }
[Required]
public int UserId { get; set; }
[ForeignKey("Id")]
[InverseProperty("Customer")]
public virtual User User { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
public class User : BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[MaxLength(32)]
[RegularExpression(#"^[\w]+(\.?[\w\d_]+)?$")]
public string Login { get; set; }
[Required]
[MinLength(6)]
[DataType(DataType.Password)]
[RegularExpression(#"^[\w]+(\.?[\w\d_]+)?$")]
public string Password { get; set; }
[Required]
[StringLength(32)]
[DataType(DataType.EmailAddress)]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")]
public string Email { get; set; }
[Required]
public string Firstname { get; set; }
[Required]
public string Lastname { get; set; }
[MaxLength(256)]
public string ProfilePhoto { get; set; }
[Required]
[ForeignKey("Account")]
public int AccountId { get; set; }
[Required]
public virtual Account Account { get; set; }
[InverseProperty("User")]
public virtual ICollection<Rate> Rates { get; set; }
public int CustomerId { get; set; }
[ForeignKey("Id")]
[InverseProperty("User")]
public virtual Customer Customer { get; set; }
}
i searched did not but found solution for doing than ONLY with attributes. can anybody help me with that?
Thanks in advance!
The mistake that you're making is that you have both tables pointing to each other as having a foreign key relationship with the other. You have to pick one table as the base table and the other as being the one that has the FK in it. If you want the User table to be the base then you would do the following:
On the User class: Remove the [ForeignKey] and [InverseProperty] attributes from Customer.
On the Customer class:
[Key, ForeignKey("User")]
public int Id { get; set; }
//Other fields
public virtual User User { get; set; }
Related
in my project (Asp.net Core Web Api) I have the tables "Truck" and "UserAccount with a one to many relashionship.
[Table("UserAccount")]
public class UserAccount : BaseClass
{
// Foreign Keys
[ForeignKey(nameof(UserAccountType))]
public int UserAccountTypeId { get; set; }
[ForeignKey(nameof(Gender))]
public int GenderId { get; set; }
[ForeignKey(nameof(Truck))]
public int TruckId { get; set; }
// Properties
public string LastName { get; set; }
public string FirstName { get; set; }
public string UserName { get; set; }
[DataType(DataType.EmailAddress)]
public string Mail { get; set; }
public string Login { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
// Navigation Properties
[IgnoreDataMember]
public virtual Gender Gender { get; set; }
//public virtual Truck Truck { get; set; }
[IgnoreDataMember]
public virtual UserAccountType UserAccountType { get; set; }
public Truck Truck { get; set; }
}
[Table("Truck")]
public class Truck : BaseClass
{
// Foreign Keys
// Properties
[Column(Order = 3)]
public string Name { get; set; }
[DataType(DataType.EmailAddress)]
[Column(Order = 4)]
public string Mail { get; set; }
[Column(Order = 5)]
public string Phone { get; set; }
[Column(Order = 6)]
public string VATNumber { get; set; }
// Navigation Properties
public virtual ICollection<TruckFoodType> TruckFoodTypes { get; set; }
public virtual ICollection<TruckOption> TruckOptions { get; set; }
public ICollection<UserAccount> UserAccounts { get; set; }
}
In the method OnModelCreation into my ApplicationDbContex file I have this to create the one to many relashionship:
modelBuilder.Entity<UserAccount>()
.HasOne<Truck>(u => u.Truck)
.WithMany(t => t.UserAccounts)
.HasForeignKey(u => u.TruckId);
But when I try to populate the UserAccount table I have this error message :
"Merge instruction is in conflict with "FK_User_Account_TruckId". This conflict occurse in the database xxx table dbo.Truck column Id" (Sorry, Comes from a french translation)
I don't hunderstand why.
Can somebody help me?
Thanks
OK, stupid mistake. In some cases the TruckId field from the User Account table can be null. So I added a "?" to this fields like this : public int? TruckId { get; set; } Sorry for inconvenience
I have segmentation class which have some price range, related office and route. I want routeCountyMap table with route and county related but I can only assign county once per segmentation.
E.g. for 200-400 segmentation has A and B office and A office has E,F,G routes; if there is X county with F route, there won't be able fore 2*00-400 segmentation*. My codes are below, how can arrange it?
public class segment
{
[Key]
public Guid segmentId { get; set; }
public string name { get; set; }
public Guid organisationId { get; set; }
}
public class office
{
[Key]
public Guid officeId { get; set; }
public string name { get; set; }
public Guid segmentId { get; set; }
public segment segment { get; set; }
}
public class route
{
[Key]
public Guid routeId { get; set; }
public string name { get; set; }
public Guid officeId { get; set; }
public office office { get; set; }
}
public class county
{
[Key]
public Guid countyId { get; set; }
public string name { get; set; }
public Guid cityId { get; set; }
}
public class routeCountyMap
{
public Guid routeCountyMapId { get; set; }
public Guid routeId { get; set; }
public Guid countyId { get; set; }
public route route { get; set; }
public county county { get; set; }
}
public class user
{
[Key]
public Guid userId { get; set; }
public string name { get; set; }
}
public class routeUserMap
{
[Key]
public Guid routeUserMapId { get; set; }
public Guid routeId { get; set; }
public Guid userId { get; set; }
public route route { get; set; }
public user user { get; set; }
}
DB diagram
I am using Entity Framework. I have tried everything, searching and adding keys but Ienter image description here cannot understand what the problem is and how to resolve it.
public class Reservation
{
[Key]
public int BookingID { get; set; }
public int CustomerID { get; set; }
public int RoomID { get; set; }
public string BookingDate { get; set; }
public int Check_In { get; set; }
public int Check_Out { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public int NoOfNights { get; set; }
[ForeignKey("RoomID")]
public virtual Room Rooms { get; set; }
[ForeignKey("CustomerID")]
public virtual CustomerDetails CustomerDetail { get; set; }
public virtual ICollection<Payment> Payment { get; set; }
}
public class CustomerDetails
{
[Key]
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int PostCode { get; set; }
public string State { get; set; }
public int PhoneNumber { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
enter image description here
All tables need a primary key or you can't use Entity Framework.
I use EF's code first approach. I have the following three classes:
public class Inquiry
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public virtual ApplicationUser CreatedBy { get; set; }
public virtual Contractor Contractor { get; set; }
public IList<ApplicationUser> InquiryUsers { get; set; }
public IList<InquiryComment> Comments { get; set; }
public IList<HydroTechEmail> Emails { get; set; }
public InquiryState State { get; set; }
public List<string> Attachments { get; set; }
public DateTime? TimeOfCreation { get; set; }
public DateTime? TimeOfModification { get; set; }
}
public class HydroTechEmail
{
public Guid Id { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public string FromDisplayName { get; set; }
public string FromAddress { get; set; }
public List<string> ToDisplayName { get; set; }
public List<string> ToAddress { get; set; }
public HydroTechEmailState State { get; set; }
public DateTime? ReceivedTime { get; set; }
public virtual List<HydroTechEmailAttachment> Attachments { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser
{
public Guid Id {get;set;}
public string Firstname {get;set;}
public string Lastname {get;set;}
}
I thought EF will generate some intermediate classes for relation Inquiry -> Many Emails and Inquiry -> Many Application Users. Instead it created a foreign keys in ApplicationUser and HydroTechEmail classes to Inquiry class. How should I create this one to many relations?
The strange is that for Comments it created an intermediate table named InquiryComments.
Entity Framework will only generate intermediate tables for many-to-many relationships.
For one-to-many relationships, no intermediate tables will be created because it is not necessary.
BasketItem duplicateBasketItem = (from ph in storeDB.BasketItems
where ph.sellerSKU == newItem.sellerSKU
select ph).SingleOrDefault();
{"Invalid column name 'BasketID'."}
My Classes:
public class Basket
{
[Key]
public string BasketID { get; set; }
public virtual IList<BasketItem> BasketItems { get; set; }
public int? Count { get; set; }
public System.DateTime DateCreated { get; set; }
public Guid UserID { get; set; }
}
public class BasketItem
{
[Key]
public int BasketItemID { get; set; }
public virtual string BasketID { get; set; }
[Required]
public int sellerID { get; set; }
[Required]
public string sellerSKU { get; set; }
[Required]
public int Quantity { get; set; }
[Required]
public decimal Price { get; set; }
}
From the research i have done so far, the error is being cause due to relationships not being mapped properly. How would I map the relationship using modelbuilder
Each basket can(optional) contain many basketitems
Each BasketItem has a BaskedID(FK) to map back to the individual Basket.