【问题标题】:LINQ Lambda, need to query to a very confuse database, how should I do it?LINQ Lambda,需要查询一个非常混乱的数据库,我该怎么做?
【发布时间】:2015-08-11 13:06:41
【问题描述】:

我有这两个来自 DB 模型的表:(MVC5 应用程序)

Absence Table 中的 Period 列应该是外键并引用 TimePeriod 的主键,但不幸的是,事实并非如此,我无法将其更改为外键(表已经填充了数据),因此 Period 列基本上是 int。 (事实上​​,我正在使用外键上的数据打开一列,这是不允许我这样做的吗?)。

无论如何,我正在尝试执行 LINQ 查询以获取某年员工的缺勤情况。但是要获得那一年,我需要与 TimePeriod 进行 JOIN,而且我想获取 TimePeriod 数据以及缺席数据,这使得没有该死的外键更加困难。

我该怎么办?我应该创建一个包含 Absence 和 TimePeriod 的模型吗?我只是不知道...感谢您的帮助。有任何问题,我都在听。

这些是代表表的库类:

[Serializable] 
public class Absence
{
    public Int32 IDAbsence;
    public Int32 IDEmployee;
    public Int32 Period;
    public DateTime BeginDate;
    public DateTime? EndDate;
    public AbsenceType AbsenceType;
    public AbsenceStatus AbsenceStatus;
    public List<Justification> Justifications;
    public List<Notification> Notifications;

    public Absence() { }

    public Absence(Int32 IDAbsence, Int32 IDEmployee, Int32 Period, DateTime BeginDate, DateTime? EndDate, AbsenceType AbsenceType, AbsenceStatus AbsenceStatus, List<Justification> Justifications, List<Notification> Notifications)
    {
        this.IDAbsence = IDAbsence;
        this.IDEmployee = IDEmployee;
        this.Period = Period;
        this.BeginDate = BeginDate;
        this.EndDate = EndDate;
        this.AbsenceType = AbsenceType;
        this.AbsenceStatus = AbsenceStatus;
        this.Justifications = Justifications;
        this.Notifications = Notifications;
    }



    }

[Serializable] 
    public class TimePeriod
    {
        public Int32 IDTimePeriod;
        public DateTime? StartTime;
        public DateTime? EndTime;

        public TimePeriod() { }

        public TimePeriod(Int32 IDTimePeriod, DateTime? StartTime, DateTime? EndTime)
        {
            this.IDTimePeriod = IDTimePeriod;
            this.StartTime = StartTime;
            this.EndTime = EndTime;
        }
    }

然后我在其他类中对这些对象进行 ObjectMapping...

【问题讨论】:

  • 你能把它放在某种代码中

标签: c# sql-server linq lambda


【解决方案1】:

连接不要求模型或数据库具有适当的外键。因此,假设您的模型中有一个简单的映射:

var absences = from p in db.TimePeriods
               join a in db,Absences on p.IDTimePeriod = a.Periond
               where p.StartTime.Year = theYear
               where a.Employee.ID = theEmployeeId
               select a;

(如果映射无法处理日期字段,您可以只检查包含一年的范围。)

【讨论】:

    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多