我有一个名为File的模型,其属性CreatedOn和ModifiedOn映射到表File上的CreatedOn和ModifiedOn列。我不希望用户设置这些列的值,而是使用SQL中的函数GETDATE()来设置它们。以下是我的代码:
这是我的模型(简化测试):
'
我的模型映射到存储过程:
public class File
{
public int? Id { get; set; }
public DateTime? CreatedOn { get; set; }
public string Name { get; set; }
public DateTime? ModifiedOn { get; set; }
}
我的迁移:
public class FileMap: EntityTypeConfiguration<File>
{
public FileMap()
{
MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name")));
}
}
我的测试班:
public partial class AddInsertStoredProcedure: DbMigration
{
public override void Up()
{
CreateStoredProcedure(
"dbo.InsertFile",
p => new
{
Name = p.String(),
},
body:
@"INSERT [dbo].[Files]([CreatedOn], [ModifiedOn], [Name])
VALUES (GETDATE(), GETDATE(), @Name)
DECLARE @Id int
SELECT @Id = [Id]
FROM [dbo].[Files]
WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
SELECT t0.[Id]
FROM [dbo].[Files] AS t0
WHERE @@ROWCOUNT > 0 AND t0.[Id] = @Id"
);
/* ... */
}
运行它时,我收到异常{“过程或函数InsertFile指定了太多参数。”}。似乎EF将我的模型的所有属性传递给存储过程InsertFile,因此有额外的参数。我可以让EF仅传递属性名称吗?
答案 0 :(得分:0)
如果在存储过程中不需要属性,请尝试向属性添加属性:
[DatabaseGenerated(DatabaseGeneratedOption.None)]
如果要从存储过程中获取属性,请使用:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
并在Fluent.api中映射:
public FileMap()
{
MapToStoredProcedures(s => s.Insert(i => i.HasName("InsertFile").Parameter(f => f.Name, "Name").Result(f => f.ModifiedOn,"ModifiedOn"));
}
例如,这就是我正在使用的内容:
模型:
public partial class Order
{
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int MasterFID { get; set; }
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int ID { get; set; }
[StringLength(50)]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string Number { get; set; }
public int? OutletID { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime? OrderDate { get; set; }
[StringLength(250)]
public string Comment { get; set; }
public decimal? Sum { get; set; }
Fluent.Api Mapping:
modelBuilder.Entity<Order>()
.MapToStoredProcedures(sp =>
{
sp.Insert(i => i.HasName("web_DS_Set_DocHeaders")
.Parameter(p => p.OutletID, "mfID")
.Parameter(p => p.DocTypeID, "orType")
.Parameter(p => p.Comment, "orComment")
.Parameter(p => p.Sum, "orSum")
.Result(r => r.Number, "orNumber")
.Result(r => r.OrderDate,"orDate")
.Result(r => r.ID, "orID"));
});
在我的存储过程结束时,我有类似于返回插入行的内容:
Select orNumber, orDate, orId from Orders where --parameters for last inserted|updated row