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

时间:2016-03-25 10:16:41

标签: c# dependency-injection ef-code-first entity-framework-6

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

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

如果在配置文件中设置了<property>remote</property>,则需要从属性表中获取属性,如果是<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"} ...}

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该拒绝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;
        }
    }
}