所以这是我第一次使用EF Code做一个大型项目而且我的关系遇到了错误。这是我的模特:
public class ApplicationUser : IdentityUser
{
public override string Id { get; set; }
...
public virtual Trainer Trainer { get; set; }
public virtual Client Client { get; set; }
}
public class Trainer
{
public Trainer()
{
Client = new HashSet<Client>();
}
[ForeignKey("ApplicationUser")]
public string TrainerId { get; set; }
...
public ICollection<Client> Client { get; set; }
}
public class Client
{
[ForeignKey("ApplicationUser")]
public string ClientId { get; set; }
...
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual Trainer Trainer { get; set; }
public virtual PhysicalAddress PhysicalAddress { get; set; }
public virtual BillingInfo BillingInfo { get; set; }
}
public class PhysicalAddress
{
public string PhysicalAddressId{ get; set; }
public Client Client { get; set; }
}
public class BillingInfo
{
public string BillingInfoId { get; set; }
public Client Client { get; set; }
}
基本上我试图制作一个Seed方法来建立一个客户端。我已经有一个人正在为一个培训师工作但是因为我尝试制作客户端的不同事情而得到了一堆不同的错误。这是我试图运行的方法
var user = new ApplicationUser
{
UserName = "Client@a.com",
Email = "Client@a.com"
};
var client = new Client
{
ApplicationUser = user,
Trainer = manager.Find("Trainer@a.com", "P@ssw0rd").Trainer,
PhysicalAddress = new PhysicalAddress
{
PhysicalAddressId = Guid.NewGuid().ToString()
},
BillingInfo = new BillingInfo
{
BillingInfoId = Guid.NewGuid().ToString()
}
context.Client.Add(client);
manager.Create(user, "P@ssw0rd");
manager.AddToRole(user.Id, "Client");
我已尝试使用Fluent API映射关系,但收到错误An error occurred while saving entities that do not expose foreign key properties for their relationships
modelBuilder.Entity<Client>().HasRequired(p => p.PhysicalAddress).WithOptional(p => p.Client);
modelBuilder.Entity<Client>().HasRequired(p => p.Trainer).WithMany(p => p.Client);
modelBuilder.Entity<Client>().HasRequired(p => p.BillingInfo).WithOptional(p => p.Client);
所以我尝试将ForeignId添加到客户端模型中:
[ForeignKey("BillingInfo")]
public string BillingInfoId { get; set; }
但是得到错误Multiplicity is not valid in Role 'Client_BillingInfo_Source' in relationship 'Client_BillingInfo'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
我不知道还有什么可以尝试,请指出我做错了什么
更新:
花了几个小时来解决这个问题后,我不断回到这个错误Referential integrity constraint violation. A Dependent Role has multiple principals with different values