【问题标题】:Simplest way to set default entity value in separate partial class在单独的部分类中设置默认实体值的最简单方法
【发布时间】:2014-01-23 16:31:00
【问题描述】:

这是我自动生成的客户类的开始:

namespace Winpro
{
using System;
using System.Collections.Generic;

public partial class Customer
{
    public Customer()
    {
        this.Blocked = false;
        this.Code = "#00000";
        this.RuleId = 1;
        this.LocationId = 1;
        this.Contacts = new ObservableListSource<Contact>();
    }

    public int Id { get; set; }
    public string Name { get; set;
    public System.DateTime Added { get; set; }
    ...

为什么我不能以这种方式扩展类。

namespace Winpro
{
public partial class Customer
{
    public Customer()
    {
        this.Added = DateTime.Now;
    }

寻找在单独的类中设置默认值或覆盖 SaveChanges() 方法的简单示例。

谢谢

【问题讨论】:

    标签: c# .net entity-framework class entity


    【解决方案1】:

    partial class 是一个分为多个文件的类。它仍然是一个类,你不能有两个具有相同签名的构造函数。

    你可以试试:

    • 定义一个接受 DateTime 参数的新构造函数
    • this调用默认构造函数
    • 将值分配给参数中的Added 属性


    namespace Winpro
    {
    public partial class Customer
    {
        public Customer(DateTime parameterAdded)
         : this() //call the default constructor
        {
            this.Added = parameterAdded; //DateTime.Now;
        }
    

    【讨论】:

    • 当我尝试插入 db 时仍然出现错误:The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. 虽然在默认构造函数中设置的值运行良好
    • @Carlo,这似乎是一个不同的问题,你可以看到这个问题stackoverflow.com/questions/4608734/…
    • 阅读了很多问答,甚至像stackoverflow.com/questions/21295123/… 一样问我自己的问题,但我就是不明白。当我在表单上拖动控件并调用 customerBindingSource.AddNew() 时,我想为字段设置默认值。使用默认构造函数中的值,一切正常,但不适用于我在部分类的第二部分中定义的值。也许我不明白如何使用你的例子?
    【解决方案2】:

    使用partial method

    在生成的类中

    public partial class Customer
    {
        public Customer()
        {
            this.Blocked = false;
            this.Code = "#00000";
            this.RuleId = 1;
            this.LocationId = 1;
            this.Contacts = new ObservableListSource<Contact>();
            AdditionnalInitialisation();
        }
    
        partial void AdditionnalInitialisation();
    

    在你的扩展中:

    public partial class Customer
    {
        partial void AdditionnalInitialisation()
        {
            this.Added = DateTime.Now;
        }
    }
    

    【讨论】:

    • 无法在生成的类中添加任何内容,因为如果重新生成代码,手动更改此文件将被覆盖?
    • 您使用的是哪个版本的 EF?
    猜你喜欢
    • 2018-09-27
    • 1970-01-01
    • 2016-08-12
    • 2019-11-29
    • 2013-11-03
    • 1970-01-01
    • 2019-02-17
    • 1970-01-01
    • 2013-03-19
    相关资源
    最近更新 更多