我有一个简单的实体模型
银行1 ---∞用户1 ---∞会话
在部分班级银行中,我必须在银行创建期间存储一个对象时钟设置。 是否可以从Session方法中检索此Clock对象,当然,没有传递Bank参数?
一些代码
public partial class Bank : IBank
{
私人IClock _bankClock;
public IClock Clock
{
get { return _bankClock; }
set { _bankClock = value; }
}
}
public partial class Session : ISession
public bool MyMethod()
{
var test = (dc.Session.Include("User.Bank").Where(t => t.session_id == session_id));
var temp = test.First().User.Bank.Clock.Now();
}
当调用MyMethod时,我得到的Object引用未设置为对象的实例。它被称为Clock属性。您是否有从LINQ查询中检索自定义对象的任何提示?
谢谢你,最诚挚的问候
更多代码 // CreateBank
public IBank CreateBank(string bankName, int valuePassedInCreateMethod, Clock bankClock)
{using (var dc = new Database1Entities(Functions.ToEntitiesConnectionString(connectionString)))
{
_dbField=valuePassedInCreateMethod;
bankReturn=(from c in dc.Bank
where c.bank_name == bankName
select c).First();
bankReturn.Clock = bankClock;
dc.SaveChanges();
return bankReturn;
}
}
答案 0 :(得分:1)
检查对象创建_bankClock,你为它分配了一些值吗?
看我是否接近你的要求。我得到了这个工作
static class Program
{
[STAThread]
static void Main()
{
User user = new User();
user.Bank = Bank.CreateBank("my bank", 23, new Clock());
Session session = new Session(user, "myid");
bool returned = session.MyMethod();
if (returned)
MessageBox.Show("Got it");
}
}
public class Bank
{
int value;
string bankName;
public Clock Clock;
public static Bank CreateBank(string bankName, int valuePassedInCreateMethod, Clock bankClock)
{
Bank b = new Bank();
b.Clock = bankClock;
b.bankName = bankName;
b.value = valuePassedInCreateMethod;
return b;
}
}
public class User
{
public Bank Bank;
public string type = "User.Bank";
}
public partial class Session
{
public static List<Session> Sessions;
string type;
string session_id;
User User;
public Session(User user, string session_id)
{
if (Sessions == null) Sessions = new List<Session>();
this.User = user;
this.type = user.type;
this.session_id = session_id;
Sessions.Add(this);
}
static void Add(Session session)
{
Sessions.Add(session);
}
static List<Session> Include(string type)
{
return Sessions.Where(rs => rs.type == type).ToList<Session>();
}
public bool MyMethod()
{
var test = Session.Include("User.Bank");
var test1 = test.Where(t => t.session_id == session_id);
var temp = test1.First();
var temp1 = temp.User;
var temp2 = temp1.Bank;
var temp3 = temp2.Clock;
var temp4 = temp3.Now();
if (temp4 != DateTime.MinValue)
return true;
return false;
}
}
public class Clock
{
public DateTime Now()
{
return DateTime.Now;
}
}