【问题标题】:One-to-many relationship between applicationuser and custom entityapplicationuser 和自定义实体之间的一对多关系
【发布时间】:2019-09-15 16:51:32
【问题描述】:

我收到一条错误消息,提示“ApplicationUser_Cars_Target: : Multiplicity is not valid in Role 'ApplicationUser_Cars_Target' in relationship 'ApplicationUser_Cars'。因为从属角色属性不是关键属性,所以从属角色的多重性上限必须是 '*'。 " 当我尝试更新我的数据库时,这是我的代码:

public class ApplicationUser : IdentityUser
{
    public string ProfilePicture { get;set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int PhoneNumber1 { get; set; }
    public int PhoneNumber2 { get; set; }
    public Address Address { get; set; }
    [ForeignKey("Cars")]
    public int CarId { get; set; }
    public ICollection<Car> Cars { get; set; }
}


public class Car
{
    [Key]
    public int CarId { get; set; }
    [ForeignKey("User")]
    public string ApplicationUserId { get; set; }
    public string Make { get; set; }
    public string Registration { get; set; }
    public string Color { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string Type { get; set; }
    public virtual ApplicationUser User { get; set; }
}

这是我的流利的api要求......用户注册汽车应该是可选的

        modelBuilder.Entity<ApplicationUser>().HasKey(x => x.Id)
            .HasOptional(x => x.Cars);

【问题讨论】:

    标签: asp.net-mvc entity-framework-6


    【解决方案1】:

    我想通了,首先我必须使应用程序用户表中的外键可以为空,并向 fluentAPI 添加一个 .withMany() 方法,如下所示:

    public class ApplicationUser : IdentityUser
    {
        public string ProfilePicture { get;set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int PhoneNumber1 { get; set; }
        public int PhoneNumber2 { get; set; }
        public Address Address { get; set; }
        [ForeignKey("Cars")]
        public int? CarId { get; set; }
        public ICollection<Car> Cars { get; set; }
    }
    

    还有这个: modelBuilder.Entity().HasKey(x => x.Id) .HasOptional(x => x.Cars).withMany();

    【讨论】:

    • 考虑通过点击答案附近的复选框来接受您的答案。
    猜你喜欢
    • 2022-01-12
    • 2022-01-05
    • 2015-06-29
    • 2021-04-19
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    相关资源
    最近更新 更多