如何从具有Entity框架的模型加载/保存/更新子集合?

时间:2016-03-07 16:01:44

标签: c# entity-framework

我不会使用Entity框架加载和扰乱参数列表。我尝试了很多变种,但在所有变种上都有例外。 如何实现模型的GetParamValue和SetParamValue方法?

namespace PoliteBot.Models
{
public class Param
{
    public long ParamID { get; set; }
    public virtual ChatUser ChatUser { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}
public class ChatUser
{
    public int ChatUserID { get; set; }
    public virtual ICollection<Param> Params { get; set; }
    public string GetParamValue(string paramName, ApplicationDbContext db)
    {
        return db.Params.FirstOrDefault(p => p.Name == paramName && p.ChatUser.ChatUserID == ChatUserID)?.Value;
    }
    public void SetParamValue(string paramName, string paramVal, ApplicationDbContext db)
    {
        var result = db.Params.FirstOrDefault(p => p.Name == paramName && p.ChatUser.ChatUserID == ChatUserID);
        if (result == null)
            db.Params.Add(new Param { Name = paramName, Value = paramVal, ChatUser = this });
        else
            result.Value = paramVal;
        db.SaveChanges();
    }
}
}

2 个答案:

答案 0 :(得分:1)

您需要分开您的顾虑 - 不要在模型中进行数据库访问。保持POCO并在您的操作或方法中执行数据库操作:

var chatUser = db.ChatUsers.Include(cu => cu.Params).First(cu => cu.ChatUserId == id);

现在你可以使用params的集合了:

var param = chatUser.Params.FirstOrDefault(p => p.Name == paramName);
param.Value = paramVal;
db.SaveChanges();

答案 1 :(得分:0)

您无权访问模型中的数据库。试试这个

  class Program
{
    static void Main(string[] args)
    {
        using (var db = new ApplicationDbContext())
        {
            Temp ch = new Temp();

            ch.SetParamValue("test", "test", db);
            ch.GetParamValue("test",db);
        }
    }
}


public class ApplicationDbContext : DbContext
{
    public DbSet<Param> Params { get; set; }
    public DbSet<ChatUser> ChatUsers { get; set; }
}


public class Param
{
    public long ParamID { get; set; }
    public virtual ChatUser ChatUser { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}
public class ChatUser
{
    public int ChatUserID { get; set; }
    public virtual ICollection<Param> Params { get; set; }

}
public class Temp
{
    public string GetParamValue(string paramName, ApplicationDbContext db)
    {
        return db.Params.FirstOrDefault(p => p.Name == paramName && p.ChatUser.ChatUserID == 1).Value;
    }
    public void SetParamValue(string paramName, string paramVal, ApplicationDbContext db)
    {
        var result = db.Params.FirstOrDefault(p => p.Name == paramName && p.ChatUser.ChatUserID == 1);
        if (result == null)
            db.Params.Add(new Param { Name = paramName, Value = paramVal, ChatUser = new ChatUser {ChatUserID=1 } });
        else
            result.Value = paramVal;
        db.SaveChanges();
    }
}

} 这对我有用