外连接和 Linq
所以我有以下代码:
return from a in DBContext.Acts
join artist in DBContext.Artists on a.ArtistID equals artist.ID into art
from artist in art.DefaultIfEmpty()
select new Shared.DO.Act
{
ID = a.ID,
Name = a.Name,
Artist = new Shared.DO.Artist
{
ID = artist.ID,
Name = artist.Name
},
GigId = a.GigID
};
这会加载一个 act 对象并将其从 linq 对象调整为我的域 act 对象。
正如您所看到的,我已经定义了艺术家与表演关系的外部连接。
我这样做是因为我一直想要这个表演,无论它是否有艺术家。
如果该表演确实有艺术家,那么效果非常好。
如果没有,那么代码就死了。 这就是罪魁祸首:
Artist = new Shared.DO.Artist
{
ID = artist.ID,
Name = artist.Name
},
如果我把它去掉,那就没问题了。 可以做我正在尝试的事情吗?
So I have the following code:
return from a in DBContext.Acts
join artist in DBContext.Artists on a.ArtistID equals artist.ID into art
from artist in art.DefaultIfEmpty()
select new Shared.DO.Act
{
ID = a.ID,
Name = a.Name,
Artist = new Shared.DO.Artist
{
ID = artist.ID,
Name = artist.Name
},
GigId = a.GigID
};
This loads an act object and adapts it from a linq object to my domain act object.
As you can see I have defined an outer join on the artist to act relationship.
I have done this because I always want the act, irrespective of if it has an artist.
This works really well if the act does indeed have an artist.
If it doesnt then the code dies. This is the the culprit:
Artist = new Shared.DO.Artist
{
ID = artist.ID,
Name = artist.Name
},
If I remove it, its fine. Is it possible to do what I'm attempting?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
或者,向 Shared.DO.Artist 添加一个构造函数,该构造函数采用 Artist 的 Linq 表示形式。 构造函数可以检查 null 并执行所有初始化。
Alternatively, add a constructor to Shared.DO.Artist that takes the Linq representation of Artist. The constructor can check for null and perform all initialization.
实际上......这对我来说似乎是最好的答案......
Actually... this seems the best answer for me....
您想要通过调用构造函数来创建一个新对象。 删除 Artist =,然后将 { } 替换为 ()。
You want to create a new object, by calling the constructor. Remove Artist = and then replace { } with ().