【发布时间】:2020-09-17 08:13:17
【问题描述】:
我想使用动态以便能够选择要定义的列以及我想让数据库设置DEFAULT 值的列。
有没有办法将dynamic 插入表中并返回Id?
我在 DataConnection 和 ITable<> 上尝试了各种重载,但我唯一能实现的结果是获取受影响的行数。
这是我的代码:
人员表架构
CREATE TABLE [dbo].[Person] (
[Id] BIGINT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Surname] VARCHAR (50) NOT NULL,
[BirthDate] DATE DEFAULT (getdate()) NOT NULL
);
.NET Core 控制台应用程序
public class Person
{
public uint Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public DateTime BirthDate { get; set; }
}
public class PeopleDataConnection : DataConnection
{
public PeopleDataConnection(string connectionString)
: base(ProviderName.SqlServer, connectionString)
{ }
public ITable<Person> People => this.GetTable<Person>();
}
class Program
{
static async Task Main(string[] args)
{
await using (var db = new PeopleDataConnection("Server=DESKTOP-I41VSUN;integrated Security=SSPI;Database=MotoGPRiders;"))
{
var dynamicPerson = new { Name = "Cal", Surname = "Crutchlow", BirthDate = new DateTime(1985, 10, 29) };
var person_without_id = new Person { Name = "Valentino", Surname = "Rossi", BirthDate = new DateTime(1979, 2, 16) };
var affectedRowsCount = await db.InsertAsync(dynamicPerson, nameof(Person));
affectedRowsCount = await db.People
.Value(x => x.Name, person_without_id.Name)
.Value(x => x.Surname, person_without_id.Surname)
.Value(x => x.BirthDate, person_without_id.BirthDate)
.InsertAsync();
}
Console.ReadLine();
}
}
第一个插入完成工作但不能返回Id,第二个让我选择列但不是动态的。
有没有办法做到这一点? 提前致谢!
【问题讨论】:
标签: .net orm repository linq2db