Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

entity framework - EF Code First Fluent API specifying the Foreign Key property

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe you should be able to do this:

HasRequired(t => t.Agent).WithMany().HasForeignKey(t => t.AgentId)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...