首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何有效地模拟这种关系

如何有效地模拟这种关系
EN

Stack Overflow用户
提问于 2015-04-08 23:56:45
回答 1查看 51关注 0票数 0

我有一个锻炼表,每次练习都可以是5种运动类型中的1种。有氧运动,定时活动,举重,举重和计时的组合,其他的东西)。每种不同的类型都以不同的方式存储数据(例如。有氧运动是强度和时间,时间只是分钟,重量是设定x代表x重量,其他东西可以是其他东西)。

因此,我有一个锻炼表,但不确定如何建模运动类型,并为每一种运动类型存储相关的锻炼数据。每次练习只能有一个练习类型,而每一个练习类型可以属于多个练习。

我倾向于只有一个锻炼表和一个锻炼类型表,并有一个多到一个关系,但我不知道如何最好地存储每个练习数据。

这将为实体框架6和modeled建模。

EN

回答 1

Stack Overflow用户

发布于 2015-04-09 00:35:33

我认为您的场景有利于继承(使用表-每个层次结构),下面是我建议的设计:

代码语言:javascript
复制
public Exercise 
{    
    public int ExerciseId {get;set;}

    [ForeignKey("ExerciseBaseTypeId")]
    public ExerciseBaseType ExerciseType {get;set;}

    [Required]
    public int ExerciseBaseTypeId {get;set;}

}

public ExerciseBaseType 
{
    public int BaseTypeId{get;set;}

    public Link<Exercise> Exercises {get;set;}

    //put other base properties that is common to all exercise types        
}

public Cardio : ExerciseBaseType {
    public string Intensity {get;set;}
    public int Time {get;set;}
}

public Timed : ExerciseBaseType {
    public int Duration {get;set;}
}

public Weight : ExerciseBaseType {
    public int Sets {get;set;}
    public int Weight {get;set;}
}

以下是dbcontext文件:

代码语言:javascript
复制
public class ExerciseDbContext : DbContext
{

    public ExerciseDbContext()
        : base("ExerciseDatabase"){ }
}

public DbSet<Exercise> Exercises { get; set; }

public DbSet<ExerciseBaseType> ExerciseTypes { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Exercise>()
            .HasRequired(e => e.ExerciseBaseType)
            .WithMany(ebt => ebt.Exercises)
            .HasForeignKey(e.ExerciseBaseTypeId);
}

例如,让我们添加一个定时练习,并使用id #1将其附加到练习中:

代码语言:javascript
复制
ExerciseDbContext db = new ExerciseDbContext();

var timedExercise = new Timed();
timedExercise.Duration = 60;
//set the other base properties

db.Exercises
  .Single(e => e.ExerciseId = 1)
  .ExerciseTypes.Add(timedExercise);

db.SaveChanges();

这有道理吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29527364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档