如何将SQL转换为Lambda表达式

时间:2019-03-16 09:17:31

标签: c# sql-server linq lambda linq-to-sql

在数据库中,我创建了如下表结构。

CREATE TABLE Course 
(
    Course_ID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(255) NOT NULL,
);

CREATE TABLE Student 
(
    Stu_ID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(255) NOT NULL,
    Mobile varchar(255),
    Age int,
    Course_ID int,
    FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID)
);

CREATE TABLE Subject  
(
    Sub_ID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(255) NOT NULL,
);

CREATE TABLE Teacher 
(
    Teach_ID int IDENTITY(1,1) PRIMARY KEY,
    Name varchar(255) NOT NULL,
    Mobile varchar(255)
);

CREATE TABLE Course_Subject 
(
    CouSub_ID int IDENTITY(1,1) PRIMARY KEY,
    Course_ID int,
    Sub_ID int,
    FOREIGN KEY (Course_ID) REFERENCES Course(Course_ID),
    FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);

CREATE TABLE Teacher_Subject 
(
    TeachSub_ID int IDENTITY(1,1) PRIMARY KEY,
    Teach_ID int,
    Sub_ID int,
    FOREIGN KEY (Teach_ID) REFERENCES Teacher(Teach_ID),
    FOREIGN KEY (Sub_ID) REFERENCES Subject(Sub_ID)
);

现在,我的问题是,我需要检索从某位老师那里学到的学生数据,这意味着需要检索一些从他/她那里学到的老师的学生。完成我的要求。我写这个SQL查询。

select 
    s.*
from 
    tbl_student s
inner join 
    Course_Subject tcs on s.Course_Id = tcs.Course_Id
inner join 
    Teacher_Subject tst on tst.Sub_ID = tcs.Sub_ID
inner join 
    Teacher t on t.Teach_ID = tst.Teach_ID
where 
    t.Teach_ID = @SomeTeacherId

现在,我需要将此查询转换为lambda表达式或Linq。我该怎么做?请帮我。可以使用Visual Studio生成任何可能的方法。

3 个答案:

答案 0 :(得分:2)

好吧,您可以使用EF生成到表的对象映射。并使用LINQ以稍微不同的语法重写查询:

var result = from students in tbl_student
             join subjects in Course_Subject on students.Course_Id == subjects.Course_Id
             join ts in Teacher_Subject on subjects.Sub_ID == ts.Sub_ID
             join teachers in Teacher on teachers.Teach_ID == ts.Teach_ID
             where teachers.Teach_ID == "your_value"
             select students; 

不确定这是绝对正确的查询,但希望您能理解主要思想。

答案 1 :(得分:2)

  

是否可以使用Visual Studio生成此内容??

是的,您可以使用Linq-to-SQL

对于您的查询,这可能是适当的

from kivy.config import Config
Config.set('graphics', 'multisamples', '0')
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.uix.recycleview import RecycleView
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout


kv = '''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManagement:
    transition: FadeTransition()
    RequestScreen:

<AddRequest>:
    request_text: ''    
    TextInput:        
        id: request_task
        hint_text: 'Task'
        text: root.request_text

<RequestRow>:
    size_hint_y: None
    orientation: 'horizontal'    
    pos: self.pos
    size: self.size
    BoxLayout:
        orientation: 'horizontal'        

        Label:
            size_hint_x: None
            size: 90,20
            id: id_row_request
        Button:
            size_hint_x: None
            text: 'Edit'            
            on_press: root.dispatch('on_request_edit')

<RequestsList>:
    id: rv
    viewclass: 'RequestRow'

    SelectableRecycleBoxLayout:
        spacing: 15
        default_size: 100, dp(25)
        default_size_hint: 1, None
        size_hint_y: None
        height: self.minimum_height
        orientation: 'vertical'
        multiselect: True

<RequestScreen>    
    BoxLayout:
        orientation: 'horizontal'
        GridLayout:
            rows: 2
            AddRequest:
                id: addrequest
                size_hint_y: None
                height: 90                
            RequestsList:

'''

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    pass

class AddRequest(BoxLayout, RecycleDataViewBehavior):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

class RequestRow(RecycleDataViewBehavior, BoxLayout, Label):
    index = None

    def __init__(self, **kwargs):
        self.register_event_type('on_request_edit')
        super().__init__(**kwargs)

    def refresh_view_attrs(self, rv, index, data):
        self.ids['id_row_request'].text =  data['request']
        return super(RequestRow, self).refresh_view_attrs(
            rv, index, data)

    def on_request_edit(self):
        print('pressed')

class RequestsList(RecycleView):

    data = [{'request': 'A'},
            {'request': 'B'},
            {'request': 'C'},
            {'request': 'D'},
            {'request': 'E'},
            {'request': 'F'},]

    def __init__(self, **kwargs):
        super(RequestsList, self).__init__(**kwargs)

class RequestScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

sm = Builder.load_string(kv)

class TestApp(App):
    def build(self):
        return sm

if __name__ == '__main__':
    TestApp().run()

答案 2 :(得分:0)

Lambda:

for (i = 1; i < aantalDwars; i++) { 

    var geometry2 = new THREE.CylinderGeometry( dwarsDiameter * scale , dwarsDiameter * scale , lengte2*scale , 20 );
    var material2 = new THREE.MeshBasicMaterial( {color: 0xe4734f} );
    var cylinder2 = new THREE.Mesh( geometry2, material2 );
    cylinder2.userData.type = 'cylinder';

    scene.add( cylinder2 );
    if (i = aantalDwars){
        volgendeCylinder = ((lengte*scale)/2) + uitsteekLinks
    }

    cylinder2.position.set( ((lengte*scale)/2)+volgendeCylinder2, 1 , 0);
    volgendeCylinder2 -= (dwarsMaas*scale);
    cylinder2.rotation.x = Math.PI / 2;
}