EF code first - one-to-one-or-zero - entity-framework

I have 2 entities:
public partial class GPSdevice
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public GPSdevice()
{
}
public int ID { get; set; }
public string UserName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual Truck Truck { get; set; }
}
public partial class Truck
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Truck()
{
}
public int TruckID { get; set; }
public string TruckNo { get; set; }
public string Make { get; set; }
[ForeignKey("GPSdevice")]
public int? GPSdeviceID { get; set; }
public virtual GPSdevice GPSdevice { get; set; }
}
I want to create a relationship one-to-one-or-zero (each GPSdevice can be linked to any truck (but to one and only one) or not linked at all)
I write the following code:
modelBuilder.Entity<GPSdevice>()
.HasOptional(e => e.Truck)
.WithOptionalPrincipal()
.WillCascadeOnDelete(false);
but it creates the following migration:
public override void Up()
{
AddColumn("dbo.Truck", "GPSdevice_ID", c => c.Int());
CreateIndex("dbo.Truck", "GPSdeviceID");
CreateIndex("dbo.Truck", "GPSdevice_ID");
AddForeignKey("dbo.Truck", "GPSdeviceID", "dbo.GPSdevices", "ID");
AddForeignKey("dbo.Truck", "GPSdevice_ID", "dbo.GPSdevices", "ID");
}
why it creates one more field and how to use the current field GPSdeviceID instead?
ADDED:
If I remove
public int? GPSdeviceID { get; set; }
and add MapKey:
modelBuilder.Entity<GPSdevice>()
.HasOptional(e => e.Truck)
.WithOptionalPrincipal(e=>e.GPSdevice).Map(p=>p.MapKey("GPSdeviceID"))
.WillCascadeOnDelete(false);
in result I get the following migration code:
public override void Up()
{
CreateIndex("dbo.Truck", "GPSdeviceID");
AddForeignKey("dbo.Truck", "GPSdeviceID", "dbo.GPSdevices", "ID");
}
then I get the following error:
There are no primary or candidate keys in the referenced table
'dbo.GPSdevices' that match the referencing column list in the foreign
key 'FK_dbo.Truck_dbo.GPSdevices_GPSdeviceID'. Could not create
constraint or index. See previous errors.

Use this :
public partial class GPSdevice
{
public GPSdevice()
{
}
public int ID { get; set; }
public string UserName { get; set; }
public virtual Truck Truck { get; set; }
}
public partial class Truck
{
public Truck()
{
}
public int TruckID { get; set; }
public string TruckNo { get; set; }
public string Make { get; set; }
public virtual GPSdevice GPSdevice { get; set; }
}
modelBuilder.Entity<GPSdevice>()
.HasOptional(o => o.Truck)
.WithRequired(ad => ad.GPSdevice);
modelBuilder.Entity<Truck>()
.HasKey(e => e.TruckID);

Related

Entity Framework database-first : how to add property to a model that will reference itself?

I am trying to create a Product table that will have a list of SubstitutionProducts that should reference other Product from the same table.
Model example :
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsMissing { get; set; }
public ICollection<Product> SubstitutionProducts { get; set; }
}
It is better to include the parent ID in your model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsMissing { get; set; }
public int? ParentId { get; set; }
public Product Parent { get; set; }
public ICollection<Product> SubStitutionProducts { get; set; }
}
This is how to configure DB schema via overriding OnModelCreatingmethod of your DbContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasOne(x => x.Parent)
.WithMany(x => x.SubStitutionProducts)
.HasForeignKey(x => x.ParentId).IsRequired(false);
}

EFCore Generic Repository and UnitOfWork Design Pattern

when im trying to create new data and save it, im getting error at the
public int Complete()
{
return _context.SaveChanges();
}
and error is saying me that:
The value of 'Agency.ID' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known. .
i have a Base class like that:
public class Base
{
protected Base()
{
CreatedDate = DateTime.Now;
IsDeleted = false;
ModifiedDate = null;
}
public int ID { get; set; }
public int? CreatedUserId { get; set; }
public int? ModifiedUserId { get; set; }
public string CreatedUserType { get; set; }
public string ModifiedUserType { get; set; }
public DateTime? CreatedDate { get; set; }
public DateTime? ModifiedDate { get; set; }
public bool? IsActive { get; set; }
public bool? IsDeleted { get; set; }
}
i have a Agency class like that :
public class Agency : Base
{
public Agency()
{
AgencyIsComplated = false;
}
[Required, StringLength(255)]
public string AgencyName { get; set; }
[Required, StringLength(255)]
public string AgencyPhoto { get; set; }
[Required, StringLength(255)]
public string AgencyEMail { get; set; }
[Required, StringLength(13)]
public string AgencyPhone { get; set; }
[StringLength(13)]
public string AgencyBPhone { get; set; }
[StringLength(255)]
public string AgencyInfo { get; set; }
[Required, StringLength(255)]
public string AgencyTitle { get; set; }
[Required, StringLength(255)]
public string AgencyLink { get; set; }
public int AgencyExportArea { get; set; } // Join table ile yapılacak,ayrı bir tabloda tutulacak
[Required, StringLength(255)]
public string AgencyInstagram { get; set; }
public string AgencyTwitter { get; set; }
public string AgencyFacebook { get; set; }
public string AgencyLinkedin { get; set; }
public string AgencyYoutube { get; set; }
public bool AgencyIsComplated { get; set; }
[ForeignKey("CompanyID")]
public Company Company { get; set; }
[ForeignKey("LogID")]
public Log Log { get; set; }
public virtual ICollection<AgencyCompany> AgencyCompanies { get; set; }
public virtual ICollection<User> Users { get; set; }
public virtual ICollection<Log> Logs { get; set; }
}
public class AgencyConfiguration : IEntityTypeConfiguration<Agency>
{
public void Configure(EntityTypeBuilder<Agency> builder)
{
builder.HasKey(agency => agency.ID);
builder.HasMany(a => a.Logs)
.WithOne(a => a.Agency)
.HasForeignKey(a=>a.ID)
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(us => us.Users)
.WithOne(us => us.Agency)
.HasForeignKey(au=>au.ID)
.OnDelete(DeleteBehavior.Restrict);
builder.HasMany(ac => ac.AgencyCompanies)
.WithOne(ac => ac.Agency)
.OnDelete(DeleteBehavior.Restrict);
}
}
and i have got a UnitOfWork like that:
public class UnitOfWork : IUnitOfWork
{
private TradeTurkDBContext _context;
public UnitOfWork(TradeTurkDBContext context)
{
_context = context;
RepositoryAgency = new RepositoryAgency(_context);
}
public IRepository Repository { get; private set; }
public IRepositoryAgency RepositoryAgency { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
im inheriting that ID on my Base Model.
the problem is getting solved when im not defining ID in the base model but i allready set up my mapping on it.
so how can i solve that error without using AgencyID in the Agency model ?
The foreign key is in the details (or child) table. Therefore, e.g. a user, should have an AgencyId as foreign key.
builder.Entity<User>()
.HasOne(u => u.Agency)
.WithMany(a => a.Users)
.HasForeignKey(u => u.AgencyId)
.OnDelete(DeleteBehavior.Restrict);
This key automatically points to the primary key of the master (or parent) table.
User.ID is a primary key. User.AgencyId is a foreign key which (automatically) relates to the primary key Agency.ID.
E.g. see: Configure One-to-Many Relationships using Fluent API in Entity Framework Core

Entity Framework - 6, Parent Key propagation to grand child object

public class Submission
{
public Submission()
{
this.VisitOccurrences = new HashSet<VisitOccurrence>();
}
public int SubmissionKey { get; set; } //PK
public string Version { get; set; }
public string ClientName { get; set; }
public string UserName { get; set; }
public DateTime SubmissionStartDate { get; set; }
public virtual ICollection<VisitOccurrence> VisitOccurrences { get; set; }
}
public class VisitOccurrence
{
public VisitOccurrence()
{
this.Observations = new HashSet<VoObservation>();
}
public int VisitOccurrenceKey { get; set; } //PK
//public int SubmissionKey { get; set; } //FK from submission . This is commented as this value inserted by EF in table. Refer to configuration below.
public string VisitConcept { get; set; }
public DateTime? VisitStartDate { get; set; }
public TimeSpan? VisitStartTime { get; set; }
public DateTime? VisitEndDate { get; set; }
public TimeSpan? VisitEndTime { get; set; }
public virtual ICollection<Observation> Observations { get; set; }
}
public class Observation
{
public int ObservationKey { get; set; } //PK
//public int VisitOccurrenceKey { get; set; } //FK from VisitOccurrence. This is commented as this value inserted by EF in table. Refer to configuration below.
//public int SubmissionKey { get; set; } // ***there is no relation on this column but I need to propagate value from parent class Submission to this grand child column when inserted Submission. What is the best way to do it?***
public string Element { get; set; }
public string ObservationConcept { get; set; }
public DateTime? ObservationDate { get; set; }
public TimeSpan? ObservationTime { get; set; }
}
public class SubmissionConfiguration : EntityTypeConfiguration<Submission>
{
public SubmissionConfiguration()
{
ToTable("Submission");
HasKey(p => p.Id).Property(p => p.Id).HasColumnName("SubmissionKey");
HasMany(p => p.VisitOccurrences).WithOptional().Map(m => m.MapKey("SubmissionKey"));
}
}
public class VisitOccurrenceConfiguration : EntityTypeConfiguration<VisitOccurrence>
{
public VisitOccurrenceConfiguration()
{
ToTable("VisitOccurrence");
Property(p => p.Id).HasColumnName("VisitOccurrenceKey");
HasMany(p => p.Observations).WithOptional().Map(m => m.MapKey("VisitOccurrenceKey"));
}
}
public class ObservationConfiguration : EntityTypeConfiguration<Observation>
{
public VoObservationConfiguration()
{
ToTable("Observation");
}
}
//Repository Method to insert Submission
public virtual void AddOrUpdate(Submission model)
{
Context.Entry(model).State = EntityState.Added;
Context.SaveChanges();
}
I have a Parent entity Submission, a Child entity VisitOccurrence and Grand child entity Observation. My configurations works When I inserted a Submission with child and grand child entities in it. All key columns populated in related tables. However, The above code inserts Submission and the identity generated in SubmissionKey is inserted in VisitOccurence and thus the VisitOccurenceKey in Observation table. But I'm looking for Configuration that could propagate SubmissionKey from VisitOccurence to Observation though there is no relation constraint added in database. please help.

EF Adding an additional FK?

I have the following 2 entities:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Fixture> Fixtures { get; set; }
}
public class Fixture
{
public int Id { get; set; }
public Result Result { get; set; }
public int HomeTeamId { get; set; }
public int AwayTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team AwayTeam { get; set; }
}
I have then mapped it like so:
public class FixtureMap : EntityTypeConfiguration<Fixture>
{
public FixtureMap()
{
HasRequired(x => x.AwayTeam).WithMany().HasForeignKey(x => x.AwayTeamId);
HasRequired(x => x.HomeTeam).WithMany().HasForeignKey(x => x.HomeTeamId);
}
}
But when I add a migration, EF is creating an additional FK and column to my Fixture table and I've no idea why? How can I tell it not too?
As you can see its added a column called Team_Id and created an FK from it even tho I have specified the relationship in the mapping?
use this code:
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Fixture> HomeFixtures { get; set; }
[InverseProperty("AwayTeam")]
public virtual ICollection<Fixture> AwayFixtures { get; set; }
}
public class Fixture
{
public int Id { get; set; }
public Result Result { get; set; }
public int HomeTeamId { get; set; }
public int AwayTeamId { get; set; }
[InverseProperty("HomeFixtures")]
[ForeignKey("HomeTeamId ")]
public virtual Team HomeTeam { get; set; }
[InverseProperty("AwayFixtures")]
[ForeignKey("AwayTeamId")]
public virtual Team AwayTeam { get; set; }
}
And :
public class FixtureMap : EntityTypeConfiguration<Fixture>
{
public FixtureMap()
{
HasRequired(x => x.AwayTeam).WithMany().HasForeignKey(x => x.AwayTeamId).willCascadeOnDelete(false);
HasRequired(x => x.HomeTeam).WithMany().HasForeignKey(x => x.HomeTeamId);
}
}

Code First Circular Reference Foreign Key Configuration

The following code creates foreign key errors when all code is not commented.
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public int FavoriteChildId { get; set; }
public Child FavoriteChild { get; set; }
//public int WorstChildId { get; set; }
public Child WorstChild { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
//public int ParentId { get; set; }
public Parent Parent { get; set; }
}
public class CFContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
It works if the foreign key names aren't specified but then there's no way to edit the models. Does anyone know how to specify the foreign key names?
Following the naming convention will create the proper FK's above - your code:
public int WorstChildId { get; set; }
public Child WorstChild { get; set; }
Does create the FK of WorstChildId for WorstChild. However, when I tried the code you had above, I got a multiple delete path error (Parent -> WorstChild -> ChildTable, Parent -> FavoriteChild -> ChildTable)
You can set either one, or both of your mappings to not cascade on delete, and that will fix your problem:
public class CFContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithRequiredPrincipal(p => p.WorstChild)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithRequiredPrincipal(p => p.FavoriteChild)
.WillCascadeOnDelete(false);
}
}