不能一对一添加设置 - ef codeFirst

时间:2016-04-05 11:38:50

标签: c# entity-framework ef-code-first fluent

我有以下课程:

User, Address, UserAddress
public class User
{
  public ICollection<useraddress> userAddresses { get; set; }
}

public class Address 
{
  public virtual User User { get; set; }
  public virtual Guid UserId { get; set; }
  public  UserAddress UserAddress { get; set; }
}

public class UserAddress
{
  public User User { get; set; }
  public Guid UserId { get; set; }
  public Address Address { get; set; }
  public Guid AddressId { get; set; }
}

我的结果应如下所示: enter image description here

我在UserAddressConfig中创建了以下流畅的配置:

HasKey(row => new { row.UserId,row.AddressId});

AdddressConfig

HasOptional(row => row.UserAddress).WithRequired(row => row.Address).WillCascadeOnDelete();

但是当我生成数据库时,它看起来像: enter image description here

1 个答案:

答案 0 :(得分:1)

你可以用这个:

public class User
{
    public Guid Id { get; set; }

    [InverseProperty("User")]
    public ICollection<UserAddress> UserAddresses { get; set; }
}

public class Address
{
    public Guid AddressId { get; set; }

    public UserAddress UserAddresses { get; set; }
}

public class UserAddress
{
    public Guid AddressId { get; set; }

    public Address Address { get; set; }


    [ForeignKey("UserId")]
    [InverseProperty("UserAddresses")]
    public User User { get; set; }

    public Guid UserId { get; set; }        

}

并配置流畅的api:

 modelBuilder.Entity<Address>().HasRequired(c => c.UserAddress)
 .WithOptional(c => c.Address) // or any other option
 .WillCascadeOnDelete(false);

但您也可以在用户和地址之间建立一对多关系,如下所示:

public class User
{
    public Guid Id { get; set; }

    [InverseProperty("User")]
    public ICollection<Address> Addresses { get; set; }
}

public class Address
{
    public Guid AddressId { get; set; }

    [ForeignKey("UserId")]
    [InverseProperty("Addresses")]
    public User User { get; set; }

    public Guid UserId { get; set; }
}