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

c# - Entity Framework 0..1 to 0 relation

class First
{
    [Key]
    public int Id { get; set; }
}

class Second
{
    [Key]
    public int Id { get; set; }

    public int? First_Id { get; set; }

    [ForeignKey("First_Id")]
    public First First { get; set; }
}

public class SecondMapping : EntityTypeConfiguration<Second>
{
    public SecondMapping () 
        : base()
    {
        this.HasOptional(s => s.First)
            .With ... ???
    }
}

Second may have a reference to First. But First never has a reference to Second. Is it possible to apply this mapping with Entity Framework 4.1?

EDIT: Previously, that was my solution:

this.HasOptional(s => s.First)
    .WithOptionalDependent()
    .WillCascadeOnDelete(false);

Second could contain one instance of First (dependent on some kind of Usage-Attribute). First doesn't contain any instance of Second.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

One-to-one relation is possible only if foreign key is also primary key of dependent entity. So the correct mapping is:

class First
{
    [Key]
    public int Id { get; set; }
}

class Second
{
    [Key, ForeignKey("First")]
    public int Id { get; set; }
    public First First { get; set; }
}

The reason is that to enforce one-to-one relation in the database foreign key must be unique in the Second entity. But entity framework doesn't support unique keys - the only unique value for EF is primary key. This is limitation of EF.

There is workaround described on Morteza Manavi's blog. Workaround is based on mapping association as one-to-many and enforcing uniqueness in database by introducing unique constraints in custom database initializer.


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

...