我需要在给定类中访问类属性的帮助。
例如,以以下类为例:
public partial class Account
{
private Profile _profile;
private Email _email;
private HostInfo _hostInfo;
public Profile Profile
{
get { return _profile; }
set { _profile = value; }
}
public Email Email
{
get { return _email; }
set { _email = value; }
}
public HostInfo HostInfo
{
get { return _hostInfo; }
set { _hostInfo = value; }
}在"Account“类中有一堆类属性,比如Email或Profile。现在,当我想在运行时访问这些属性时,我会这样做(对于电子邮件):
_accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify");
Account account = _accountRepository.GetAccountByUserName(username);
if(account != null)
{
account.Email.IsConfirmed = true;但是,我得到"Object reference not set...“对于account.Email..。为什么会这样呢?如何访问Account,使account.Email、account.Profile等返回给定AccountId或UserName的正确数据。
Here is a method that returns Account:
public Account GetAccountByUserName(string userName)
{
Account account = null;
using (MyDataContext dc = _conn.GetContext())
{
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}
return account;
}上面的方法很有效,但是当我尝试的时候:
account = (from a in dc.Accounts
join em in dc.Emails on a.AccountId equals em.AccountId
join p in dc.Profiles on em.AccountId equals p.AccountId
where a.UserName == userName
select a).FirstOrDefault();我的电子邮件和配置文件仍收到对象引用异常
属性。这只是一个SQL问题,还是我需要执行其他操作才能完全访问Account类中的所有属性?
谢谢!
发布于 2010-05-27 01:28:28
您是自己声明这些属性,还是尝试从Linq- to -SQL中指示某种自动生成的代码?
如果这是在Account表引用Email表等情况下自动生成的,那么您可能只需要在加载选项中指定希望加载这些对象:
using (MyDataContext dc = _conn.GetContext())
{
var options = new DataLoadOptions();
options.LoadWith<Account>(a => a.Email);
options.LoadWith<Account>(a => a.Profile);
options.LoadWith<Account>(a => a.HostInfo);
dc.LoadOptions = options;
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}发布于 2010-05-27 00:56:46
你得到这个是因为电子邮件是另一个尚未分配的类。你能做的就是在你的构造函数中默认将链接到其他类的属性作为新的项。例如,在ctor中:
public Account()
{
// Set Defaults
Email = new Email();
Profile = new Profile();
HostInfo = new HostInfo();
}然后,您可以根据需要设置它们的值。
发布于 2010-05-27 00:59:58
这看起来像是处理属性上的空值。如果您希望对电子邮件属性进行存储或查询,则应将其初始化为null以外的值,或者更改查询以使其能够处理空值。另外,如果您从数据库获取空值,并且您的属性不能设置为null,则会发生相反的问题。
https://stackoverflow.com/questions/2915035
复制相似问题