Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 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 Reply

0 votes
by (71.8m points)

I believe you should be able to do this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...