根据类型(列)映射到集合

时间:2015-07-26 16:13:50

标签: c# entity-framework ef-code-first

我有三个实体: Series,Argument,ArgumentType

public class Series : Entity<int>
{
    public string Name { get; set; }

    public DateTime CreateDateTime { get; set; }

    public DateTime? ChangeDateTime { get; set; }

    public virtual ICollection<Argument> Arguments { get; set; }

    //public virtual ICollection<Argument> LambdaArguments { get; set; }
    //public virtual ICollection<Argument> GradientArguments { get; set; }
}

public class Argument : Entity<int>
{
    public ArgumentType Type { get; set; }
    public Series Series { get; set; }
    public int Value { get; set; }
}

public class ArgumentType : Entity<int>
{
    // 'Lambda', 'Gradient' etc.
    public string Code { get; set; }
}

我想知道是否有可能以及如何映射系列实体可以拥有依赖于 ArgumentType 本身的每个参数的集合:

public virtual ICollection<Argument> LambdaArguments { get; set; }
public virtual ICollection<Argument> GradientArguments { get; set; }

我收到了映射文件:

public class SeriesMap : BaseMap<Series, int>
{
    public SeriesMap()
    {
        Property(x => x.Name).IsRequired();
        Property(x => x.CreateDateTime).IsRequired();
        Property(x => x.ChangeDateTime).IsOptional();

        HasMany(x => x.Arguments);
    }
}

public class ArgumentMap : BaseMap<Argument, int>
{
    public ArgumentMap()
    {
        Property(x => x.Value).IsRequired();
        HasRequired(x => x.Series);
        HasRequired(x => x.Type);
    }
}

public class ArgumentTypeMap : BaseMap<ArgumentType, int>
{
    public ArgumentTypeMap()
    {
        Property(x => x.Code);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用this inheritance model(每个层次结构表)来实现此目的。你最终会得到这些模型:

public abstract class Argument : Entity<int>
{
    public ArgumentType Type { get; set; }
    public Series Series { get; set; }
    public int Value { get; set; }
}

public class GradientArgument: Argument 
{
    //..extra properties
}

public class LambdaArgument: Argument 
{
    //..extra properties
}

映射:

public class ArgumentMap : BaseMap<Argument, int>
{
    public ArgumentMap()
    {
        Property(x => x.Value).IsRequired();
        HasRequired(x => x.Series);
        HasRequired(x => x.Type);
         Map<Argument>(m => m.Requires("Type").HasValue("Course"))
            .Map<GradientArgument>(m => m.Requires("Type").HasValue("GradientArgument"))
            .Map<LambdaArgument>(m => m.Requires("Type").HasValue("LambdaArgument"));
    }
}

然后,您可以将参数类型附加到Series实体。您必须强制转换类型以检索任何自定义属性。