依赖注入在本地和远程数据之间进行选择

Dependency injection to choose between local and remote data

我需要创建一个模型,动态选择数据源作为模型的 属性(代码首先来自数据库。代码其次)。

class MyModel{
public int MyModelId {get; set;}
...
public int PropertyId {get;set;}
public virtual Property Property {get;set;} // this what I need to choose.
...

属性 需要从 属性 table 从数据库获取,如果在配置文件中设置 <property>remote</property> 并且从具有相同结构的本地容器获取来自数据库 if <property>local</property>.

class Property{
   public int PropertyId {get;set}
   public string name {get;set;}
   public virtual ICollection<MyModel> MyModels {get;set;}
   public Property()
   {
       MyModels = new List<Model>();
   }
}

本地数据如

 List<Property> lProperty = new List<Property>() 
{{PropertyId = 1,name = "val1"},
{PropertyId = 2,name = "val2"},
{PropertyId = 3,name = "val3"} ...}

在这种情况下你应该拒绝EF关系并写这样的东西:

public class MyModel
{
    public int MyModelId { get; set; }

    //PropertyId now is not real FK to PropertyTable at DB it is just another column, 
    //but it still will store reference to Property
    public int? PropertyId { get; set; }

    [NotMapped]
    public Property Property
    {
        get
        {
            if (PropertyId.HasValue)
            {
                if (ForExampleStaticClass.config("property") == "remote")
                    using (var context = new Context())
                    {
                        return context.PropertyTable.Where(x => x.PropertyId == PropertyId.Value).FirstOrDefault();
                    }
                else
                    return ForExampleStaticClass.lProperty.Where(x => x.PropertyId == PropertyId.Value).FirstOrDefault();
            }
            else
                return null;
        }
        set
        {
            //I consider that Property(value) already exists at DB and/or Local Storage.                          
            PropertyId = value.PropertyId;
        }
    }
}