0

I have a question.

I have these two tables: Tables

The principal table is User with Customer dependence.

The reverse engineer code first generated classes as follows:

public class User
{
    public User()
    {
        this.Customers = new List<Customer>();          
    }

    ...

    public virtual ICollection<Customer> Customers { get; set; }

}

public class Customer
{
    public Customer()
    {
    }

    ...

    public int UserID { get; set; }
    public virtual User User { get; set; }

}

I made the following modification in the user class:

public class User
{
    public User()
    {          

    }
    public int CustomerID { get; set; }
    public virtual Customer Customer { get; set; }

}

Because the relationship is One-to–Zero-or-One.

The original mapping is this:

// Relationships
        this.HasRequired(t => t.User)
            .WithMany(t => t.Customers)
            .HasForeignKey(d => d.UserID);

And the modified mapping is this :

this.HasRequired(t => t.User)
            .WithOptional(t => t.Customer)
            .Map(m => m.MapKey("UserID"));

Is That correct? If not, how would this mapping?

Thanks.

4

1 回答 1

2

不,这是不正确的。

你能做的最好的事情——假设你可以改变数据库模式——是UserID从表中删除外键Customer,然后在数据库中创建两个主键之间的关系,这Customer.CustomerID就是关联中的外键。

然后逆向工程应该自动创建预期的一对一关系,如下所示:

public class Customer
{
    public int CustomerID { get; set; }
    public virtual User User { get; set; }
    //...
}

public class User
{
    public int UserID { get; set; }
    public virtual Customer Customer { get; set; }
    //...
}

//...

this.HasRequired(t => t.User)
    .WithOptional(t => t.Customer);

如果您无法更改数据库模式,最好的办法是仅从类中删除集合ICollection<Customer> Customers并将User关系保持为一对多。

这一切的原因是EF只支持共享主键一对一关联,不支持外键一对一关联。(后一个你只能通过删除集合来“伪造”,但从 EF 的角度来看,它仍然是一对多的。)

您可以在此处阅读有关与 EF 的一对一关联及其限制的更多信息:

于 2012-11-03T19:27:15.010 回答