I have a class AgentBalance with an association to Agent, thus:
public class AgentBalance { ... public int AgentId { get; set; } public virtual Agent Agent { get; set; } }
AgentId is detected as the FK for the Agent relationship by convention, but I want to make it explicit in the Mapping class, to be safer against future changes. If Agent had a collection of Balances then I know how to do this e.g.:
HasRequired(t => t.Agent).WithMany(a => a.Balances).HasForeignKey(t => t.AgentId);
However, Agent does not have a collection of Balances - I don't want that association to be reverse navigable. But without the .WithMany in the mapping I don't get the option to specify .HasForeignKey. Is there another way? (N.B. I know I could also do this using attributes, but I want to use the fluent API mapping).
The [ForeignKey(name)] attribute can be applied in three ways: [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity. [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.
The Entity Framework Core Fluent API HasForeignKey method is used to specify which property is the foreign key in a relationship. In the following example, the AuthorFK property in the Book entity does not follow Entity Framework Core's convention for foreign key names.
When you change the relationship of the objects attached to the context by using one of the methods described above, Entity Framework needs to keep foreign keys, references, and collections in sync.
The only way to configure composite keys is to use the HasKey method. You specify the properties that form the composite key by passing them in as properties of an anonymous type to the HasKey method.
I believe you should be able to do this:
HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)
I prefer to use Data Annotations for these tasks, not Fluent API. It is much shorter end easy to understand. EF must detect properties ended with "Id" automatically, but to be on a safe side you can specify them explicitly:
using System.ComponentModel.DataAnnotations.Schema; ... public int AgentId { get; set; } [ForeignKey("AgentId")] public virtual Agent Agent { get; set; }
You will need to specify them explicitly if your FK prop are not ended with "Id", for example:
public int AgentCode { get; set; } [ForeignKey("AgentCode")] // now this is needed if you'd like to have FK created public virtual Agent Agent { get; set; }
You can find more details here: https://msdn.microsoft.com/en-us/data/jj591583.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With