A
A
AntiVassal2021-02-24 21:29:57
.NET
AntiVassal, 2021-02-24 21:29:57

How to properly set up relationships in Entity Framework Core?

There are two models:

[Table("params")]
    public class ParamModel {
        [Key]
        [Column("id")]
        public int Id {
            get; set;
        }
        [Column("name")]
        public string Name {
            get; set;
        }
        [Column("value")]
        public string Value {
            get; set;
        }
        [Column("algorithm")]
        public int AlgorithmID {
            get; set;
        }
        public AlgorithmModel Algorithm {
            get; set;
        }
    }
    [Table("algorithms")]
    public class AlgorithmModel {
        [Key]
        [Column("id")]
        public int Id {
            get; set;
        }
        [Column("name")]
        public string Name {
            get; set;
        }
        public List<ParamModel> Params {
            get; set;
        }
    }

The links are built like this:
modelBuilder.Entity<AlgorithmModel>().HasMany(p => p.Params).WithOne(p => p.Algorithm).
                HasForeignKey(p => p.AlgorithmID);
            modelBuilder.Entity<ParamModel>().HasOne(p => p.Algorithm).WithMany(p => p.Params).
                HasForeignKey(p=>p.AlgorithmID);

But when I read the Params property from the AlgorithmModel, I get null. (database full) How to fix?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman, 2021-03-19
@AntiVassal

Somehow it's not very nicely done. The [Column("name")] attributes are redundant. I understand that one algorithm has several parameters, so I would add the ForignKey attribute to the AlgorithmID and the virtual modifier to the List list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question