Software development tutorials and demos lasting no more than 60 seconds.
No in-depth explanations, no off-topic rants, and no slides. One small topic per video - only code, console, config, and client.
All videos come with a corresponding blog entry, and all code is available on GitHub.
SQL Server Table Valued Parameters with .NET
Get link
Facebook
X
Pinterest
Email
Other Apps
-
privatestatic SqlDataRecord CreatePersonRecord(int id,string name){var metaData =new[]{new SqlMetaData("Id", SqlDbType.Int),new SqlMetaData("Name", SqlDbType.VarChar,50)};var record =new SqlDataRecord(metaData);
record.SetInt32(0, id);
record.SetString(1, name);return record;}private SqlDataRecord[] GetPersonRecords(){
retun new[]{ CreatePersonRecord(1,"John Doe"), CreatePersonRecord(2,"Jane Doe")};}using(var conn =new SqlConnection(cs)){
conn.Open();using(var comm = conn.CreateCommand()){
comm.CommandText ="dbo.TestPerson";
comm.CommandType = CommandType.StoredProcedure;var peopleParmsValue = GetPersonRecords();if(!peopleParmsValue.Any()){
peopleParmsValue =null;// Don't set the value to an empty array}
comm.Parameters.Add(new SqlParameter {
ParameterName ="@people",
Value = peopleParmsValue,
SqlDbType = SqlDbType.Structured,
TypeName ="dbo.PersonType"});using(var rdr = comm.ExecuteReader()){while(rdr.Read()){
Console.WriteLine("{0}: {1}", rdr["Id"], rdr["Name"]);}}}}
If you need a left join in Entity Framework, you have a couple options. First, if you’re using a real foreign key that just happens to be nullable, then you can use the regular navigation properties. But if you’re doing a left join manually, or with other factors, then you need to do things just a little differently: Suppose we have the following database: create table dbo . Foods ( FoodID int not null identity primary key , FoodName varchar ( 100 ) not null ) ; go insert dbo . Foods ( FoodName ) values ( 'Pizza' ) , ( 'Chicken' ) , ( 'Potatoes' ) , ( 'Broccoli' ) ; go create table dbo . People ( PersonID int not null identity primary key , FirstName varchar ( 100 ) not null , FavoriteFoodID int null , constraint FK_Person_FavoriteFoodID foreign key ( FavoriteFoodID ) references dbo . Foods ( FoodID ) ) ; go insert dbo . People ( FirstName , FavoriteFoodID ) values ( 'John' , 1 ) , ...
With .NET 5, you get a new concept called record . Lots of cool things, one of which is that you can serialize and deserialize with JSON just like a class, except you don't need to define properties one at a time, or even the body of the type. Apparently XML serialization doesn't quite work, so stick with JSON. View code on GitHub
Comments
Post a Comment