简体   繁体   English

如何将EF CodeFirst多重性从一变为零/一?

[英]How to change EF CodeFirst multiplicity from one to zero/one?

Imagine I have two entities: 假设我有两个实体:

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

public class Country{
    public Guid CountryId {get; set;}
    public virtual List<User> Users {get; set;}
}

If I try to add a user who doesn't belong to any country, I get an UpdateException on the SaveChanges command: 如果尝试添加不属于任何国家的用户,则SaveChanges命令会出现UpdateException

Entities in 'SLContext.User' participate in the 'Country_Users' relationship. “ SLContext.User”中的实体参与“ Country_Users”关系。 0 related 'Country_Users_Source' were found. 找到0个相关的'Country_Users_Source'。 1 'Country_Users_Source' is expected 1个“ Country_Users_Source”

I believe this issue is related to the autogenerated one-to-many relationship. 我相信这个问题与自动生成的一对多关系有关。 How can I set this multiplicity to 0.1 ---> * ? 如何将多重性设置为0.1 ---> *?

If you are using FluentAPI , configuration for User Entity should be : 如果使用FluentAPI ,则User实体的配置应为:

   HasOptional(x=> x.Country)
       .WithMany(x=> x.Users);

And your User Entity : 和您的用户实体:

   public class User{
        public Guid UserId { get; set; }
        public virtual Country Country { get; set; }
   }

Hope this help. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 EF Core从多重性为零或一的模型中获取实体的导航属性 - EF Core get Navigation Properties of an entity from Model with multiplicity Zero or One EF可选的一对多多重性错误 - EF optional one to many multiplicity error EF CodeFirst,一对多,完全相同 - EF CodeFirst, one to many, EXACTLY IEnumerable EF CodeFirst:DropCreateDatabaseIfModelChanges除了一个表 - EF CodeFirst: DropCreateDatabaseIfModelChanges except one table 实体框架4.1 Codefirst:删除一对多子项时出现“给定多重性约束”错误 - Entity Framework 4.1 Codefirst: “Given multiplicity constraints” error when deleting one-to-many children 不能一对一流利地添加设置-ef code - cant add setting with fluent in one-to-one - ef codeFirst 使用CodeFirst的C#一对零或一个关系 - C# One-To-Zero-Or-One relationship using CodeFirst CodeFirst EF4.1 MVC针对遗留数据库 - 多重性冲突 - CodeFirst EF4.1 MVC Against legacy database - Multiplicity conflicts EF6如何映射这个零或一对一的关系 - EF6 how to map this zero or one to one relationship 多重性在角色1中无效。*或EF奇怪的迁移代码或如何在一个DB中存储两组完全不同的用户 - Multiplicity is not valid in Role 1..* OR EF weird migration code OR how to store two separate sets of completely different users in one DB
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM