从存储过程返回一个复杂类型
问题
您希望在模型使用存储过程中返回一个复杂类型。
解决方案
让我们说,你有一个Employee实体模型。Employee包含员工的身份证、名称和一个复杂的地址类型,保存员工的地址、城市、州和邮政编码(address, city, state, 和 ZIPcode)。复杂类型的名称是员工地址。在员工实体的属性是简单的地址。
您要使用存储过程返回雇员地址复杂类型的实例的集合。存储过程返回的地址如下:
create procedure [dbo].[GetEmployeeAddresses] (@city varchar(50)) as begin select [Address], City, [State], ZIPcode from Employee where City = @city end
1、右键单击设计面,并从数据库中选择更新模型。在对话框中,选择“GetEmployeeAddresses”存储过程。单击“完成”将存储过程添加到模型中。
2、右键单击设计图面上,并选择“添加➤函数导入。选择从所存储的过程名称下拉列表中GetEmployeeAddresses。在函数导入名称文本框中,输入GetEmployeeAddresses。这将是模型中的方法的名称。选择“复杂的返回类型”,并在下拉菜单中选择“ EmployeeAddress”。单击“确定”。
3、调用存储过程
using (var context = new School5Entities()) { var emp1 = new Employee { Name = "Lisa Jefferies", Address = new EmployeeAddress { Address = "100 E. Main", City = "Fort Worth", State = "TX", ZIPcode = "76106" } }; var emp2 = new Employee { Name = "Robert Jones", Address = new EmployeeAddress { Address = "3920 South Beach", City = "Fort Worth", State = "TX", ZIPcode = "76102" } }; var emp3 = new Employee { Name = "Steven Chue", Address = new EmployeeAddress { Address = "129 Barker", City = "Euless", State = "TX", ZIPcode = "76092" } }; var emp4 = new Employee { Name = "Karen Stevens", Address = new EmployeeAddress { Address = "108 W. Parker", City = "Fort Worth", State = "TX", ZIPcode = "76102" } }; context.Employees.Add(emp1); context.Employees.Add(emp2); context.Employees.Add(emp3); context.Employees.Add(emp4); context.SaveChanges(); } using (var context = new School5Entities()) { Console.WriteLine("Employee addresses in Fort Worth, TX"); foreach (var address in context.GetEmployeeAddresses("Fort Worth")) { Console.WriteLine("{0}, {1}, {2}, {3}", address.Address, address.City, address.State, address.ZIPcode); } }
执行结果