C# 实体框架代码优先-在域模型上使用接口

C# 实体框架代码优先-在域模型上使用接口,c#,.net,entity-framework,ef-code-first,domain-driven-design,C#,.net,Entity Framework,Ef Code First,Domain Driven Design,假设你有一个停车场,每个停车场可以容纳x辆车,每辆车可以有不同的属性。像这样: public class CarPark { public int Id { get; set; } public ICollection<ICar> Cars { get; set; } } public interface ICar { string Model { get; set; } } public class Volvo : ICar { public

假设你有一个停车场,每个停车场可以容纳x辆车,每辆车可以有不同的属性。像这样:

public class CarPark
{
    public int Id { get; set; }

    public ICollection<ICar> Cars { get; set; }
}

public interface ICar
{
    string Model { get; set; }
}

public class Volvo : ICar
{
    public string Model { get; set; }

    public string Color { get; set; }
}

public class Bmw : ICar
{
    public string Model { get; set; }

    public int Wheels { get; set; }
}
公共级停车场
{
公共int Id{get;set;}
公共i收集车{get;set;}
}
公共接口ICar
{
字符串模型{get;set;}
}
公共级沃尔沃:ICar
{
公共字符串模型{get;set;}
公共字符串颜色{get;set;}
}
公共级宝马:ICar
{
公共字符串模型{get;set;}
公共整数轮{get;set;}
}

当模型不同时,您如何处理这种情况

假设您的意思是如何处理由于接口而导致的模型映射混乱:您可以在DbContext的OnModelCreation方法中手动配置模型的转换


查看此处了解更多信息:

我找到了一个解决方案,我没有使用创建抽象类的接口,而是调整了上面的代码以显示它是如何完成的:

public class CarPark
{
    public int Id { get; set; }

    public virtual ICollection<Car> Cars { get; set; }
}

public abstract class Car
{
    public int Id { get; set; }

    public string Model { get; set; }
}

[Table("Volvo")]
public class Volvo : Car
{
    public string Color { get; set; }
}

[Table("Bmw")]
public class Bmw : Car
{
    public int Wheels { get; set; }
}
公共级停车场
{
公共int Id{get;set;}
公共虚拟ICollection Cars{get;set;}
}
公共抽象类汽车
{
公共int Id{get;set;}
公共字符串模型{get;set;}
}
[表(“沃尔沃”)]
大众级沃尔沃:汽车
{
公共字符串颜色{get;set;}
}
[表(“宝马”)]
公共级宝马:汽车
{
公共整数轮{get;set;}
}
由于表注释,每辆车将在一个单独的表中结束,此策略称为TPT-table Per Type,如果删除该属性,则所有车将在同一个表中结束,此策略称为TPH-table Per Hierarchy

这个例子很糟糕,但假设每辆车都是一个具有独特设置或类似设置的支付提供商

更多信息: