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
276 views
in Technique[技术] by (71.8m points)

c# - Create association on non-primary key fields with Entity Framework 4.1 Fluent API

We are using EF 4.1 and the fluent API to get data from a legacy database (that we are not permitted to change). We are having a problem creating a relationship between two tables where the related columns are not primary and foreign keys.

With the classes below, how would we configure the one-to-many relationship between Report and RunStat such that Report.RunStats would return all of the RunStat entities where the ReportCode fields are equal?

public class Report
{
    [Key]
    public int ReportKey { get; set; }
    public string Name { get; set; }
    public int ReportCode { get; set; } // Can we associate on this field?
    public virtual ICollection<RunStat> RunStats { get; set; }
}

public class RunStat
{
    [Key]
    public int RunStatKey { get; set; }
    public int ReportCode { get; set; }
    public DateTime RunDate { get; set; }
}

Basically, I want to use the Fluent API to configure EF such that it considers Report.ReportCode to be the foreign key and RunStat.ReportCode to be the primary key.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is not possible. Relations in EF follows exactly same rules as in the database. It means that principal table must have unique identifier which is referenced by dependent table. In case of database the identifier can be either primary key or unique column(s) of principal table. Otherwise it is not valid relation.

Entity framework doesn't support unique keys. If you want to have one-to-many relation between Report and RunStat your dependent table (RunStat) must contains column with value of Report.ReportKey. There is no other way to make it automatic - otherwise you must simply make it custom property and fill it from entity framework manually when you need it.


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

...