今天使用一对多的使用小记!
两个表UserInfo 和 Sort 一对多关系
[Table(Name="userInfo")]
public class UserInfo
{
[Column(IsDbGenerated=true,IsPrimaryKey=true)]
public int id { set; get; }
[Column]
public string userName { set; get; }
[Column]
public string pwd { set; get; }
[Column]
public int age { set; get; }
}
[Table(Name="Score")]
public class Score
{
[Column]
int id { set; get; }
[Column]
public int chinese{set;get;}
[Column]
public int english { set; get; }
[Column]
public int userId { set; get; }
}
class Demo
{
static void Main(string[] args)
{
DataContext ds = new DataContext("server=.;database=demodb;user=sa;pwd=sa");
Table<UserInfo>userInfos=ds.GetTable<UserInfo>();
Table<Score>scores=ds.GetTable<Score>();
//两张表内联
var user = from u in userInfos join s in scores on u.id equals s.userId select new { UserName=u.userName,Pwd=u.pwd,Age=u.age};
foreach(var userInfo in user)
Console.WriteLine(string.Format("{0},{1},{2}",userInfo.UserName,userInfo.Pwd,userInfo.Age));
}
}
//以上形式比较显示体现了两表连接 ,是否可以自动关联起来 答案那是肯定的,,,,
在UserInfo中添加对多方的Score的引用
//userId 是在Score中引用UserInfo的一个外键 是集合 理论上可以理解成IList<Score>
[Association(OtherKey="userId")]
public EntitySet<Score> Scores { set; get; }
在Score中体现一的一方 也就是UserInfo
添加
private EntityRef<UserInfo> userInfo;
////userId是Score表中的外键
[Association(Storage="userInfo",ThisKey="userId",IsForeignKey=true)]
public UserInfo UserInfo
{
get { return userInfo.Entity; }
set { userInfo.Entity = value; }
}
测试:
DataContext ds = new DataContext("server=.;database=demodb;user=sa;pwd=sa");
Table<UserInfo>userInfos=ds.GetTable<UserInfo>();
var user = from u in userInfos where u.id==1 select u;
UserInfo userInfo = user.Single<UserInfo>();
if (userInfo != null)
{
Console.WriteLine("用户:" + userInfo.userName);
foreach (Score s in userInfo.Scores)
{
Console.WriteLine(string.Format("语文成绩:{0} 英语成绩{1}", s.chinese, s.english));
}
}
//查询用户的时候 其成绩也是已经加载到了该用户中了。
DataContext ds = new DataContext("server=.;database=demodb;user=sa;pwd=sa");
Table<Score> Scores = ds.GetTable<Score>();
var score = from s in Scores where s.id == 1 select s;
Score scoreTest = score.Single<Score>();
Console.WriteLine(string.Format("用户:{0} 语文成绩:{1}",scoreTest.UserInfo.userName,scoreTest.chinese));
查询成绩也会加载出该用户!