0

这个问题就像我之前的第 2 部分一样!

以下是我学到并希望是真的事情:

  1. 不要将数据实体上下文用作静态
  2. 使用后处理数据上下文 - 通常在一次之后 -
  3. 将参数传递给 UPDATING Entity 方法而不是 Entity(我将解释它,在这里我的十字路口在于)

这是我修改后的代码:

public class ManagerBase
    {
        private NoxonEntities _entities = null;

        public NoxonEntities Entities
        {
            get
            {
                if (_entities == null)
                    _entities = new NoxonEntities();

                return _entities;
            }
        }
    }

//Managers uses ManagerBase class as a Base class
MemberManager currentMemberManager = new MemberManager();
currentMemberManager.Save(memberId, username, password, languageId);


//MemberManager class
public Member Save(long memId, string username, string password, int langId)
        {
            using (var Context =   base.Entities)
            {
                var Data = Context.Member.First(c => c.Id == memId);

                Data.Username = username;
                Data.Password = password;
                Data.Language = Context.Language.First(c => c.Id == langId); //Gets the foreign entity

                Context.SaveChanges();

                return Data;
            }
        }

这毫无例外地有效。但通常这个SAVE方法是由接口实现的方法。所以,我宁愿将一个OBJECT值传递给 SAVE 方法,而不是像上面那样传递所有字段。例如我想用这个:

//Member is an EntityFramework Object which was created during EF Model when I added by visual studio
//Filter is the method that returns an EntityFramework Object from EF (and eventually database) with given some arguments
//SomeArguments could be  MemberId = 2
Member modifiedMember = currentMemberManager.Filter(someArguments);
modifiedMember.UserName = "newvalue";
currentMemberManager.Save(modifiedMember);

在 SAVE 方法中,也许我可以这样使用:

public Member Save(Member modifiedMember)
            {
                using (var Context =   base.Entities)
                {
                    var Data = Context.Member.First(c => c.Id == modifiedMember.Id);

                    Data.Username = modifiedMember.Username;
                    Data.Password = modifiedMember.Password;
                    Data.Language = Context.Language.First(c => c.Id == modifiedMember.LanguageId); //Gets the foreign entity

                    Context.SaveChanges();

                    return Data;
                }
            }

如果我要像上面那样使用它,我认为我不应该使用传递对象 EF Object,而是应该使用我将编写的一些其他类来将参数映射到 EF 成员实体。

第一个问题:这是一个好方法吗?

public class MyMember
{
    public long Id { set; get; }
    public string Username { set; get; }
    public string Password { set; get; }
    public int LanguageId { set; get; }
}

MyMember.Username = "NewValue";
MyMember.LanguageId = 4; //4 as in new value
currentMemberManager.Save(MyMember); //As you can see MyMember is not an EF Entity in here

但这需要很长时间,因为已经有一些书面代码。

第二个问题:我不能在OUTSIDE使用 EF Entity 对象并在那里修改它以将其保存在MemberManager类中吗?

再次,非常感谢您提前提供的帮助。

4

1 回答 1

0

这是答案:

如何更新实体?

我感谢那些帮助过我的人。

于 2012-09-19T07:47:23.437 回答