[英]Selecting a single item with linq2sql query
I'm trying to retrieve a single entity from a Linq2Sql query, but I'm having trouble finding the 'pretty' way of doing it. 我正在尝试从Linq2Sql查询中检索单个实体,但是我很难找到做到这一点的“漂亮”方法。 Here's what I've found that works: 这是我发现的有效方法:
var states = from state in dc.States where state.Id == j.StateId select state;
State s = states.ToList<State>().ToList()[0];
I'm hoping this isn't the best way of getting the entity. 我希望这不是获取实体的最佳方法。 :-P :-P
Anyone have a better solution? 有人有更好的解决方案吗?
Thanks in advance! 提前致谢!
--J --J
try this: 尝试这个:
int stateID = getTheStateIDToLookup();
State state = dc.States.SingleOrDefault(s => s.StateID == stateID);
var s = dc.States
.SingleOrDefault(st => st.Id == j.StateId);
Also keep in mind that this requires that there by only one state which matches your criteria, which is probably true in your case. 还请记住,这仅需要一个符合您条件的状态,这在您的情况下可能是正确的。 Or you could use: 或者您可以使用:
var s = dc.States
.FirstOrDefault(st => st.Id == j.StateId);
Or you could get rid of the OrDefault like so if you KNOW there is a state which matches your criteria: 否则,您可以像这样摆脱OrDefault,如果您知道存在符合您条件的状态:
var s = dc.States
.Single(st => st.Id == j.StateId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.