0

我是 Linq to SQL 的新手。我有 5 个字段,它们都存在于 20 个表中。我创建了一个包含 5 个字段的基类。然后我创建了 20 个继承自这个基类的类。Linq 无法映射到它们。经过一番搜索,我发现我应该通过在属性上方添加一个InheritanceMapping和一个Column属性来处理这个问题。但这对我不起作用。

这是一个似乎可以预期的示例:

[InheritanceMapping(Type = typeof(Motorcycle), IsDefault = true, Code = 1)]
[Table]
public class Vehicle
{
    [Column]
    public string Make { get; set; }

    [Column]
    public string Model { get; set; }

    [Column(IsDiscriminator = true, Name="VehicleTypeId")]
    public VehicleType VehicleType { get; set; }
}

public class Motorcycle : Vehicle
{
    // implementation here
}

这对我不起作用,因为VehicleTypeId数据库中没有字段。我真正要做的就是在其他方面不相关的类中应用 5 个字段。这就是我真正想做的事情:

public enum BaseTypes {
    AnyClassAtAll = 1,
    SomeOtherClass = 2
}

public abstract class BaseClass {
    [Column(Name = "Record_Inserted", DbType = "datetime", CanBeNull = false)]
    public DateTime RecordInserted { get; set; }

    // This column does not exist in the database and
    // is only added for inheritance for Linq
    [Column(IsDiscriminator = true)]
    public BaseTypes BaseType;
}

[InheritanceMapping(Type = typeof(AnyClassAtAll), Code = BaseTypes.AnyClassAtAll)]
public class AnyClassAtAll : BaseClass {
    [Column(Name = "FOO", DbType = "nvarchar(100)")]
    public string Foo { get; set; }

    public AnyClassAtAll() {
        BaseType = BaseTypes.AnyClassAtAll;
    }
}

Linq 失败,因为它无法将任何内容映射到该BaseType字段。

4

1 回答 1

0

根据我之前的评论,您可以定义一个interface指定共享列的:

public interface IVehicleBaseProperties
{
    DateTime RecordInserted{get;set;}
    string Make{get;set;}
    string Model {get;set;}
    VehicleType VehicleType{get;set;}
    //etc.

}

然后创建部分类文件(请记住 L2S 将映射类创建为部分类,以便您可以扩展它们)

public partial class MotorCycle:IVehicleBaseProperties
{
}

请注意,您不需要做更多的事情,因为只要RecordInserted, Make,Model等出现在自动生成 partial的 中,那么界面就满足了。

无论如何,您现在可以传递 Bikes、Cars、Batmobiles 等的实例,IVehicleBaseProperties因为任何“通用”函数只能在这些通用属性上运行,因为这些类实际上并不相关。

希望有帮助。

于 2013-11-14T20:04:14.377 回答