Linq到EF - 连接列名

时间:2013-11-19 04:32:56

标签: c# linq entity-framework

为了简洁,我将案件保持在3。我其实想要8.有没有办法做这样的事情?我可以连接我想要访问的列名(例如,ph.Img + ph.ImgCount.toString()),我想要结果:“ph.Img1”?

using (evEntities ent = new evEntities())

PostHousing ph = (from p in ent.PostHousings
                                  where p.HousingPostID == "24"
                                  select p).FirstOrDefault();

ph.Img + ph.ImgCount.toString() = completeFilePath
ent.SaveChanges();

这样可以省去写出带有8个case语句的长开关/案例。

PostHousing ph = (from p in ent.PostHousings
                                  where p.HousingPostID == stringPostID
                                  select p).FirstOrDefault();

                switch (ph.ImgCount)
                {
                    case null:
                        ph.Img1 = completeFilePath;
                        break;
                    case 1:
                        ph.Img2 = completeFilePath;
                        break;
                    case 3:
                        ph.Img3 = completeFilePath;
                        break;

                }

1 个答案:

答案 0 :(得分:1)

您可以使用反射来执行此操作:

typeof(PostHousing).GetProperty("Img" + ((ph.ImgCount ?? 0) + 1))
    .SetValue(ph, completeFilePath);

请注意,我将null更改为0并添加1,因为这是您的switch语句正在执行的操作。