Custom one-to-many relationship in EF 6.1 - c#

Is it possible to write custom logic for a one-to-many relationship? Suppose I have the following classes:
public class ProductIncompatibility
{
[Key]
public int ProductIncompatibilityId { get; set; }
public int ProductIdA { get; set; }
public int ProductIdB { get; set; }
[ForeignKey("ProductIdA")]
public virtual Product ProductA { get; set; }
[ForeignKey("ProductIdB")]
public virtual Product ProductB { get; set; }
}
public class Product
{
[Key]
public int ProductId { get; set; }
public virtual ICollection<ProductIncompatibility> IncompatibleProducts { get; set; }
}
When I execute the following Linq-query:
Products.Select(it => new { it.ProductId, it.IncompatibleProducts })
or
Products.Include("IncompatibleProducts")
I would expect all ProductIncompatibility-records where ProductIdA = ProductId || ProductIdB = ProductId.
Is it possible to specify this logic, for example using the modelBuilder?

Related

How do I set up a one-to-many relationship using Entity Framework Core?

I'm working on a trucking API using Entity Framework (EF) Core. Basic CRUD operations are working fine using the repository pattern. There is an error in
configurations I am implementing, however.
I want to obtain multiple trailers and trucks associated with single load, reflecting the one-to-many relationship.
public class LoadConfiguration : IEntityTypeConfiguration<Load>
{
public void Configure(Microsoft.EntityFrameworkCore.Metadata.Builders.EntityTypeBuilder<Load> builder)
{
builder.Property(p=>p.Id).IsRequired();
builder.HasOne(t=>t.Customer).WithMany().HasForeignKey(p=>p.CustomerId);
builder.Property(p=>p.LoadedFrom).IsRequired();
builder.HasMany(p=>p.Trailer).WithOne().HasForeignKey(t=>t.TrailerId);
builder.HasMany(p=>p.Truck).WithOne().HasForeignKey(t=>t.TruckId);
builder.Property(p=>p.Destination).IsRequired();
}
}
public class Truck:BaseEntity
{
public int PlateNo { get; set; }
public string ModelName { get; set; }
public Location StateCode { get; set; }
public int PollutionCertificateValidity { get; set; }
public int DateOfPurchase { get; set; }
public int FitnessCertificateValidity { get; set; }
}
public class Load:BaseEntity
{
public Customer Customer { get; set; }
public int CustomerId { get; set; }
public string LoadedFrom { get; set; }
public Trailer Trailer { get; set; }
public int TrailerId { get; set; }
public Truck Truck { get; set; }
public int TruckId { get; set; }
public string Destination { get; set; }
}
public class Trailer:BaseEntity
{
public int TrailerCapacity { get; set; }
public Truck Truck { get; set; }
public int TruckId { get; set; }
}
public class BaseEntity
{
public int Id { get; set; }
}
A one-to-many relationship is defined by using navigation collections, that has the capacity to hold many Trucks and Trailers. You can choose the collection type freely, but I would suggest ICollection generic type.
Modify your Load class as follows:
public class Load:BaseEntity
{
public Customer Customer { get; set; }
public int CustomerId { get; set; }
public string LoadedFrom { get; set; }
public string Destination { get; set; }
// navigation collections
public ICollection<Trailer> Trailers { get; set; }
public ICollection<Truck> Trucks { get; set; }
}
You will then be able to set up the relationship in your LoadConfiguration class by using
the pluralized name:
builder.HasMany(p=>p.Trailers).WithOne();
builder.HasMany(p=>p.Trucks).WithOne();
.. even though EF Core will be smart enough to figure out the relation by convention so the fluent configuration is redundant.

EntityFramework navigation property not working as expected

I have the following 3 (simplified) classes setup in entity framework
public class Service
{
[Key]
public int ServiceId { get; set; }
public int WorkformId { get; set; }
[ForeignKey("WorkformId")]
public virtual Workform Workform { get; set; }
}
public class Workform
{
[Key]
public int WorkformId { get; set; }
[ForeignKey("WorkformId")]
public virtual ICollection<FieldMap> FieldMaps { get; set; }
}
public class FieldMap
{
[Key]
public int FieldMapId{ get; set; }
public int WorkformId{ get; set; }
}
And if I try to do something like this
var service = db.Services.Include("Workform.FieldMaps")
.FirstOrDefault(p => p.ServiceId == serviceId);
service.Workform.FieldMaps is pulling the entire collection, not just the records with the matching relational id.
Am I missing some here?

Entity framework with many one-to-zero-or-one relationships

I want to implement many one-to-zero-or-one relationships in one entity, but I am having problems getting it to work then generating the migration for it.
public class Invoice
{
public int Id { get; set; }
public int? MorningExpenseId { get; set; }
public int? EveningExpenseId { get; set; }
public Expense MorningExpense { get; set; }
public Expense EveningExpense { get; set; }
}
public class Expense
{
public int Id { get; set; }
public int InvoiceId { get; set; }
public Invoice Invoice { get; set; }
}
modelBuilder.Entity<Invoice>()
.HasOptional<Expense>(p => p.MorningExpense)
.WithRequired(g => g.Invoice);
modelBuilder.Entity<Invoice>()
.HasOptional<Expense>(p => p.EveningExpense)
.WithRequired(g => g.Invoice);
But I am getting an error of Schema specified is not valid. Errors: The relationship '...' was not loaded because the type '...' is not available..
I also was experimenting with using a primary composite key in the ´Expense´ class like:
public enum ExpenseType { Morning, Evening };
public class Expense
{
public int Id { get; set; }
public ExpenseType ExpenseType { get; set; }
public Invoice Invoice { get; set; }
}
But also no luck with getting it to work. How this should be implemented using Fluent API?
In Entity framework, appliation types must match Database types. Relationships must have the virtual keywork.
You must code like this
public class Invoice
{
public int Id { get; set; }
public int MorningExpenseId { get; set; }
public int EveningExpenseId { get; set; }
public virtual Expense MorningExpense { get; set; }
public virtual Expense EveningExpense { get; set; }
}
public class Expense
{
public int Id { get; set; }
public int InvoiceId { get; set; }
public virtual Invoice Invoice { get; set; }
}

Join 3 tables using Entity Framework

How can I build a model using Entity Framework to join 3 tables?
At the moment I have:
public class KeywordAdCategory
{
[Key]
[Column("Keyword_Id", Order = 0)]
public int Keyword_Id { get; set; }
[Key]
[Column("Ad_Id", Order = 1)]
public int Ad_Id { get; set; }
[Key]
[Column("Category_Id", Order = 2)]
public int Category_Id { get; set; }
}
But I don't have any navigation properties.
Is there a better way to build a relashionship between 3 tables using Entity Framework?
Also the Keyword, Ad and Category models:
public class Keyword
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
}
public class Ad
{
// Primary properties
[Key]
public int Id { get; set; }
// Navigation properties
public AdOperation AdOperation { get; set; }
public Member Member { get; set; }
public Address Address { get; set; }
public Category Category { get; set; }
public virtual ICollection<Picture> Pictures { get; set; }
private ICollection<Feature> _features;
public virtual ICollection<Feature> Features
{
get { return _features ?? (_features = new HashSet<Feature>()); }
set { _features = value; }
}
}
public class Category
{
// Primary properties
public int Id { get; set; }
public int? CategoryParent_Id { get; set; }
public int? CategoryGroup_Id { get; set; }
public bool IsActive { get; set; }
// Navigation properties
public Keyword Keyword { get; set; }
}
Thanks.
I'm assuming that you're using Code-First Entity Framework here, and that you have your KeywordAdCategory object in your database as well. In which case, just simply do the following in your KeywordAdCategory class to do the proper mapping:
[Key, ForeignKey("Keyword")]
[Column("Keyword_Id", Order = 0)]
public int Keyword_Id { get; set; }
[Key, ForeignKey("Ad")]
[Column("Ad_Id", Order = 1)]
public int Ad_Id { get; set; }
[Key, ForeignKey("Category")]
[Column("Category_Id", Order = 2)]
public int Category_Id { get; set; }
public virtual Keyword Keyword { get; set; }
public virtual Ad Ad { get; set; }
public virtual Category Category { get; set; }
Doing this should do the proper mappings, put FKs on your KeywordAdCategory table, and thus give you the ability to have good navigation properties to the other objects.

One to many in Entity Framework using fluent mapping

Im trying to do a one-to-many map by using fluent api.
This is my classes
public class Product : EntityBase
{
public Product()
{
this.ProductArticles = new List<ProductArticle>();
}
[Key]
public int ProductId { get; set; }
public string Description { get; set; }
public string ReportText1 { get; set; }
public string ReportText2 { get; set; }
public bool Standard { get; set; }
public int ProductGroupId { get; set; }
public decimal? Surcharge1 { get; set; }
public decimal? Surcharge2 { get; set; }
public decimal? Surcharge3 { get; set; }
public decimal? Surcharge4 { get; set; }
public decimal PriceIn { get; set; }
public decimal PriceOut { get; set; }
public decimal PriceArtisanIn { get; set; }
public decimal PriceArtisanOut { get; set; }
public decimal PriceTotalIn { get; set; }
public decimal PriceTotalOut { get; set; }
public decimal PriceTotalOutVat { get; set; }
public decimal PriceAdjustment { get; set; }
public bool Calculate { get; set; }
public string Notes { get; set; }
[ForeignKey("ProductGroupId")]
public virtual ProductGroup ProductGroup { get; set; }
public virtual ICollection<ProductArticle> ProductArticles { get; set; }
}
public class ProductArticle : EntityBase
{
[Key]
public int ProductArticleId { get; set; }
public int ProductId { get; set; }
public int ArticleId { get; set; }
public decimal Qty { get; set; }
public decimal PriceIn { get; set; }
public bool Primary { get; set; }
public virtual Product Product { get; set; }
public virtual Article Article { get; set; }
}
Now i want from single Product include all ProductArticles
This is my mapping
public class ProductMap : EntityTypeConfiguration<Product>
{
public ProductMap()
{
// Primary Key
this.HasKey(p => p.ProductId);
// Table & Column Mappings
this.ToTable("Product");
this.HasMany(p => p.ProductArticles)
.WithOptional()
.Map(p => p.MapKey("ProductId").ToTable("ProductArticle"));
}
But it doesnt work.. Please help :)
First - by convention EF treats property with name equal to Id or EntityTypeName + Id is a primary key. So, you don't need to configure that manually.
Second - if you don't want table names to be plural, just remove that convention from your context instead of providing table name for each entity mapping:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
base.OnModelCreating(modelBuilder);
}
And last - EF smart enough to define foreign keys which have names like RelatedEntityTypeName + Id. So, you don't need any fluent configurations here.

Categories