简体   繁体   English

如何创建与另一个 class 的多个关系作为不同的属性?

[英]How to create multiple relations to another class as different properties?

I want to create class that contains multiple objects as a relation to another table.我想创建包含多个对象作为与另一个表的关系的 class。

For example, if I wanted to implement a team of three players using different objects instead of a collection, my code would've looked like this:例如,如果我想使用不同的对象而不是集合来实现由三个玩家组成的团队,我的代码将如下所示:

public class Team
{
    [Key]
    public int TeamId { get; set; }

    public string Name { get; set; }

    [ForeignKey("Goalkeeper")]
    [Required]
    public int GoalkeeperId { get; set; }
    public virtual Player Goalkeeper { get; set; }

    [ForeignKey("Defender")]
    [Required]
    public int DefenderId { get; set; }
    public virtual Player Defender { get; set; }

    [ForeignKey("Striker")]
    [Required]
    public int StrikerId { get; set; }
    public virtual Player Striker { get; set; }
}

public class Player
{
    [Key]
    public int PlayerId { get; set; }

    public string Name { get; set; }

    [ForeignKey("Team")]
    public int TeamId { get; set; }
    public virtual Team Team { get; set; }
}

Trying to create a migration based on this code I'm getting an error:尝试基于此代码创建迁移时出现错误:

Unable to determine the relationship represented by navigation property 'Player.Team' of type 'Team'.无法确定“团队”类型的导航属性“Player.Team”表示的关系。 Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。

What am I missing?我错过了什么? Is this even a correct approach to implement this?这甚至是实现这一点的正确方法吗?

I think that the problem is that EF Core cannot automatically detect what's the correct way of configure the mapping between the entities.我认为问题在于 EF Core 无法自动检测配置实体之间映射的正确方法。

From the docs :文档

When there are multiple navigation properties defined between two types (that is, more than just one pair of navigations that point to each other) the relationships represented by the navigation properties are ambiguous.当在两种类型之间定义了多个导航属性时(即不止一对相互指向的导航),导航属性表示的关系是不明确的。 You will need to manually configure them to resolve the ambiguity.您将需要手动配置它们以解决歧义。

Therefore, you should try to configure it manually in your DbContext .因此,您应该尝试在DbContext中手动配置它。 It would be something ish like this, but I might have a mistake somewhere since I didn't test it.这将是这样的事情,但由于我没有测试它,所以我可能在某个地方有错误。

public class YourDatabaseContext : SqlContext
    {
        ...

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Team>()
                .HasOne(x => x.Goalkeeper )
                .WithOne()
                .HasForeignKey<Team>(t => t.GoalkeeperId);

            modelBuilder.Entity<Team>()
                .HasOne(x => x.Defender)
                .WithOne()
                .HasForeignKey<Team>(t => t.DefenderId);

            modelBuilder.Entity<Team>()
                .HasOne(x => x.Striker)
                .WithOne()
                .HasForeignKey<Team>(t => t.StrikerId);
        }
    }

PD: I usually prefer this method of configuring the relationships with the FluentAPI instead of polluting the model with Attributes. PD:我通常更喜欢这种使用 FluentAPI 配置关系的方法,而不是用属性污染 model。 To further organize the code, you can create a class extending IEntityTypeConfiguration<SomeEntity> per entity where you put the configuration code, and then in your DbContext.OnModelCreating you can add this line to scan your assembly an add all configurations:要进一步组织代码,您可以创建一个 class 扩展IEntityTypeConfiguration<SomeEntity>每个放置配置代码的实体,然后在您的DbContext.OnModelCreating中添加此行以扫描您的程序集并添加所有配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

暂无
暂无

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

相关问题 如何为一个类创建具有相同属性但值与每个对象不同的多个对象 - how to create multiple objects with same properties for a class but values are different to each object 如何使用具有不同类的多个属性的 linq `Except`? - How to use linq `Except` with multiple properties with different class? 在一个类中拥有多个类的不同属性 - Holding different properties of multiple classes in one class 如何创建具有 1 个已知属性的泛型方法。 想要使用 Generic Class 属性动态获取不同类中的属性 - How to Create a generic method with 1 known property. Want to dynamic get the properties in different class with Generic Class property 如何从另一个类访问一个类的属性 - How to access the properties in a class from another class 如何让一个 function 创建多个不同类型的相同 class - How to have one function create multiple different types of the same class 如何创建类的(多态)集合/列表/数组,其中每个类可能具有一些不同的属性 - How to create a (Polymorphism) collection/list/array of a class where each one may have some different properties 如何从两个不同的属性创建DependencyProperty - How to create DependencyProperty from two different properties 在 C# 中创建每次都可以具有不同属性的类或对象 - Create an class or an object that can have different properties everytime in C# 如何在类中创建一组方法/属性? - How to create a group of methods/properties within a class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM