In Linq to SQL I could specify a relationship that didn't have to depend on the foreign keys and pks existing in the database, useful for creating composite relationships like this:
public class Equipment_CableNormalised
{
...
[Association(ThisKey = "EquipmentId,PortNumber", OtherKey = "EquipmentId,PortNumber", IsForeignKey = false)]
public List<EquipmentPort> EquipmentPorts
{
get; set;
}
}
This then generated the sql similar to " .. join EquipmentPorts EP on EP.EquipmentId = blah and EP.PortNumber = Blah".
Can I do the same sort of thing in EF4.1 (using annotations or fluent api)? I know you can specify composite keys and use the [Keys] and [ForeignKeys] attributes, but this relationship doesn't map to keys...
How does the sample relation from your code works? I expect that EquipementId must be either PK or unique key (not supported in both L2S and EF) on one side because otherwise the relation could not exist (both one-to-one and one-to-many demands unique principal). Once it is PK on one side the port number is redundant.
Code first allows only mapping to keys. If you have existing database you can cheat it in your model and map new relations in the same way as you would map existing but you still have to follow simple rule - properties in principal are primary keys, properties in dependent entity are mapped as foreign keys.
If you want EF to generate DB for you, you will always have all relations in the database.
Use HasKey http://www.ienablemuch.com/2011/06/mapping-class-to-database-view-with.html
Either use HasKey, put this on OnModelCreating
modelBuilder.Entity<SalesOnEachCountry>().HasKey(x => new { x.CountryId, x.OrYear });
Or use Key Column Order
public class SalesOnEachCountry
{
[Key, Column(Order=0)] public int CountryId { get; set; }
public string CountryName { get; set; }
[Key, Column(Order=1)] public int OrYear { get; set; }
public long SalesCount { get; set; }
public decimal TotalSales { get; set; }
}
Regarding your question about foreign key, I haven't yet tried the pure code(OnModelCreating) approach, perhaps you can just put two ForeignKey attribute on child class itself, might need to put Column Order too.
This could be the answer composite key as foreign key
That answer confirms my hunch that you could put two ForeignKey attributes on child class itself.
Related
Im utilsing a code first approach for the first time (Ive previously always used database first) and am trying to understand some basic concepts. If I create a foreign key relationship between two entities, how does entity framework know which properties (columns) to use in the two sides of the relationship ? My question is probably better explained with a simple code example. I have two entities, patient and treatment. A patient can have multiple treatments so there will be a one to many relationship between the patient and the treatment, with a foreign key relationship existing between the two entities. Here are my entity classes. Please note these are greatly simplified for the sake of explanation.
public class Patient
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<PatientTreatment> PatientTreatment { get; set; }
}
public class PatientTreatment
{
public int Id { get; set; }
public string TreatmentDescription { get; set; }
public int PatientId { get; set; }
public virtual Patient Patient { get; set; }
}
So for the patient entity the primary key would be Id and for the PatientTreatment entity, its primary key would also be Id
For the foreign key relationship, according to what Ive googled so far, the code above will create that relationship for me, is this correct ? If so, how would entity framework know that the PatientId in PatientTreatment is linked to Id in the Patient entity ? This is how its supposed to be in the database (SQL Server), but I cant see how entity framework would know this. Im really new to the code first approach so Im just trying to understand how this would work. Could anyone explain this to me ?
Ive also read that setting the relationship as above doesnt create indexes (PatientId in PatientTreatment) so these have to be created in code as well
EF works with conventions, as Caius mentioned.
In your case:
EF knows that there are two entity object - Patient and PatientTreatment, because dbSet and optional configuration exist for those classes.
Patient contains so called navigation property leading to PatientTreatment's - a collection, but it could be most of the things implementing IEnumerable - EF assumes that You want to create relationship here.
Patient have an Id field - EF by naming convention without any configuration will assume that this is an entity key. Same goes for PatientTreatment
PatientTreatment has a navigation property to a single Patient - this, again, by convention tells EF that you want the relationship between this two entities to be one-to-many - collection on one side, single reference on the other side.
Ofc one to many could also be possible by convention even without navigation property in PatientTreatment - just to be clear.
I have an audit-tracking like system, that contains the following two entities:
The JobCreate entity:
public class JobCreate
{
[Key] public string JobId { get; set; }
public List<AffectedEntity> AffectedEntities { get; set; }
}
And the AffectedEntity entity:
public abstract class AffectedEntity
{
[Required]
public string JobId { get; set; }
public int Id { get; set; }
[CanBeNull] public JobCreate Job { get; set; }
}
So far this is just a normal foreign key relation:
modelBuilder.Entity<JobCreate>()
.HasMany(j => j.AffectedEntities)
.WithOne(a => a.Job)
.HasForeignKey(a => a.JobId)
.IsRequired(false)
.OnDelete(DeleteBehavior.Cascade);
Entity Framework generates a foreign key for this relationship. My problem with this is that this audit system is event driven, which means it receives the events that creates the AffectedEntity and the event that creates the JobCreate entries out of order. In other words, the JobCreate entity might not yet exist when the AffectedEntity is created. However as far as the domain goes, this is actually fine. So how do I model that in Entity Framework? I want to be able to "navigate" along that connection from JobCreate to AffectedEntity, however the other direction is not necessary.
the JobCreate entity might not yet exist when the AffectedEntity is created. However as far as the domain goes, this is actually fine. So how do I model that in Entity Framework?
Just have the relationship in the EF model, but omit it or set the FK to not be enforced in the back-end. EG in SQL Server you would set the Foreign Key Constraint to NOCHECK.
Just beware that EF may assume that the FK is enforced when it creates queries. EG if you query db.AffectedEntities.Inclue("JobCreate") it may use an INNER JOIN and not return any AffectedEntities without a JobCreate.
And if you need to deal with AffectedEntities with a null JobID, you'd have to change the data type to int?.
I've read as many posts as I can on this topic but none of the solutions I have tried seem to work. I have an existing database and created a new Code First From Existing Database project.
I have a base table called Thing. Every object has a record in this table using Id as the Unique Primary Key. Each other object inherits from this but they use the same Id in the child tables without using a new Identity column in the sub tables. Effectively giving each 'Thing' a unique Id:
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Car
{
public int Id { get; set; }
//other properties
}
public class Person
{
public int Id { get; set; }
//other properties
}
public class Color
{
public int Id { get; set; }
//other properties
}
Every new record first creates an item in 'Thing' and then using that Id value creates a new record in its respective table, creating multiple 1 to 0..1 relationships where the Id field on the derived tables is also the FK to Thing.
Thing 1 to 0..1 Car
Thing 1 to 0..1 Person
Thing 1 to 0..1 Color
and so on
I have tried many different Data Annotation and Fluent API combinations but it always comes back to the same error:
'Unable to retrieve metadata for Model.Car'. Unable to determine the principal end of association between the types 'Model.Thing' and 'Model.Car'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.'
I did manage to get past this error by using virtual with the inverse annotation and setting the Id field to be Key and ForeignKey, but then the message jumps to Person. If you then set it up the same as Car the message reverts back to Car.
It seems I could go back and create a normal Foreign Key to each child table, but that is a lot of work and I am sure it is possible to get this working somehow. Preferably using fluent API.
If you are going to use Data Annotations, you need to declare the PK of the dependent entity as FK too:
public class Thing
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Car Car{get;set;}
}
public class Car
{
[Key,ForeignKey("Thing")]
public int ThingId { get; set; }
//other properties
public virtual Thing Thing{get;set;}
}
And if you are going to use Fluent Api (remove the attributes from your model), the configuration would be like this:
modelBuilder.Entity<Car>().HasRequired(c=>c.Thing).WithOptional(t=>t.Thing);
Based on the multiplicity that is specified, it only makes sense for Thing to be the principal and Car to be the dependent, since a Thing can exist without a Car but a Car must have a Thing.
As you can see you don't need to specify that ThingId is the FK of this relationship.This is because of Entity Framework’s requirement that the primary key of the dependent be used as the foreign key. Since there is no choice, Code First will just infer this for you.
Update
Reading again your question I think you are trying to create a hierarchy. In that case you could use the Table per Type (TPT) approach.
I have an entity which is already being used with an underlying database, and it was created with just the navigational property to an optional entity (1:0..1). So by default conventions, EF created a nullable foreign key column in the DB and gave it the "MyProp_Id" name with underscore, according to that convention.
Now, I wish to expose that foreign key as a property on the entity, because it will make certain scenarios easier for me. I don't want to rename/change the underlying foreign key column in the DB (the MyProp_Id one). In fact, there shouldn't be any underlying DB updates, I just want to expose that FK on the entity. A code sample to clarify:
public class MyEntityA
{
public long Id { get; set; }
//public long? MyOptionalEntityB_Id { get; set; } <== this is what I am trying to add
//public long? MyOptionalEntityBId { get; set; } <== this didn't work either
public MyEntityB MyOptionalEntityB { get; set; }
}
I've tried just simply adding the "MyOptionalEntity_Id" property as property on the entity, hoping that EF would "automagically" see that because the names are the same, it would just map and be happy. NO DICE.
Then I tried to name my property "MyOptionalEntityId" (no underscore), but still NO DICE.
Then I tried adding an explicit mapping configuration to say:
this.Property(p => p.MyOptionalEntityId).HasColumnName("MyOptionalEntity_Id");
NO DICE
Is there a way to do this? Is this clear and make sense?
Try adding foreign key attribute.
public long? MyOptionalEntityB_Id { get; set; }
[ForeignKey("MyOptionalEntityB_Id")]
public MyEntityB MyOptionalEntityB { get; set; }
Or using fluent api.
modelBuilder.Entity<MyEntityA >()
.HasOptional(x => x.MyOptionalEntityB)
.WithMany().HasForeignKey(x => x.MyOptionalEntityB_Id);
// ^^^ -> if MyEntityB has collection of MyEntityA, mention it
I have a Video class and a MediaContent class that are linked by a 1-1, required:required relationship: each Video must have exactly 1 associated MediaContent. Deleting a MediaContent object must result in the deletion of the associated Video object.
Using the fluent API, the relationship can be modeled as follows:
modelBuilder.Entity<Video.Video>()
.HasRequired(v => v.MediaContent).WithRequiredPrincipal(mc => mc.Video)
.WillCascadeOnDelete(true);
When adding a migration to reflect this change in the database, this is how the relationship gets transcribed in terms of foreign keys:
AddForeignKey("MediaContents", "MediaContentId", "Videos", "VideoId", cascadeDelete: true);
Updating the database, I get the following error:
Cascading foreign key 'FK_MediaContents_Videos_MediaContentId' cannot be created where the referencing column 'MediaContents.MediaContentId' is an identity column.
Dropping the WillCascadeOnDelete(true) property removes the error, but I'm not sure I understand why. Shouldn't the error appear whether or not cascading is turned on? The way I understand the problem, the error comes from the fact that the generation of VideoId and MediaContentId is handled by auto-increment (or by whatever the id generation strategy is), potentially contradicting the foreign key constraint. But I can't see what this has to do with delete-cascading...
What am I missing? More generally, how would you go about modeling a cascadable one-to-one, required:required relationship with EF?
I avoid the modelBuilder cruft approach and use simple POCOs and attributes generally - which you can use to accomplish your goals like so:
public class Video
{
public int Id { get; set; }
// Adding this doesn't change the db/schema, but it is enforced in code if
// you try to add a Video without a MediaContent.
[Required]
public MediaContent MediaContent { get; set; }
}
public class MediaContent
{
[ForeignKey("Video")]
public int Id { get; set; }
public Video Video { get; set;}
}