c# LINQ to Entities: retrieve custom objects
I've got an easy entity model
Bank 1---∞ User 1---∞ Session
In partial class Bank i've got to store an object Clock set during Bank creation. Is it possible to retrieve this Clock object from inside a Session method and, of course, no Bank parameter passed?
Some code
public partial class Bank : IBank
{
private 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();
}
when calling MyMethod i get Object reference not set to an instance of an object. and it is referred to the Clock property. Have you got any hints to retrieve a custom object from a LINQ query?
Thank you, Best Regards
more code //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;
}
}
Check object creation _bankClock, have you assigned some value to it?
See if I am close to your requirement. I get this working
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;
}
}
精彩评论