簡體   English   中英

非必需 object 字段上的實體框架驗證錯誤

[英]Entity Framework validation error on non-required object field

我有一個 ASP.NET MVC 網站,它將 ViewModel 傳遞給 WebAPI 服務,以便首先使用實體框架代碼對數據庫中的對象執行 CRUD 操作。

我的域實體對象之一是業務,它具有業務信息、地址、主要聯系人和次要聯系人。 問題是,不需要輔助聯系人 object,因為並非所有公司都會有輔助聯系人。 我已將 ID 字段設置為可為 null,但是當我嘗試將新業務記錄保存到沒有輔助聯系人 object 的數據庫時,它給我實體驗證錯誤,提示輔助聯系人記錄字段是必需的。

有誰知道如何阻止這個錯誤,這樣我就可以在沒有輔助聯系人的情況下將業務實體保存在數據庫中?

下面是相關代碼。 我在我的視圖模型和模型之間使用自動映射器到 map。

域名業務 Object

    public class Business
{
    public Guid PrimaryContactId { get; set; }
    [ForeignKey("PrimaryContactId")]
    [Required]
    public virtual Contact PrimaryContact { get; set; }

    public Guid? SecondaryContactId { get; set; }
    [ForeignKey("SecondaryContactId")]
    public virtual Contact SecondaryContact { get; set; }

    [Key]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(100)]
    public string CompanyName { get; set; }

    [MaxLength(100)]
    public string CompanyWebsite { get; set; }

    [Required]
    [MaxLength(100)]
    public string Industry { get; set; }

    [Required]
    public NumberOfEmployees NumberOfEmployees { get; set; }

    [Required]
    public CommunicationPreference CommunicationPreference { get; set; }

    public Guid AddressId { get; set; }

    [ForeignKey("AddressId")]
    [Required]
    public virtual Address Address { get; set; }
}

業務查看 Model

public class BusinessViewModel
{
    public Guid PrimaryContactId { get; set; }
    public PrimaryContactViewModel PrimaryContact { get; set; }

    public Guid? SecondaryContactId { get; set; }
    public SecondaryContactViewModel SecondaryContact { get; set; }

    public Guid Id { get; set; }

    [DisplayName("Company Name")]
    [Required]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public string CompanyName { get; set; }

    [DisplayName("Company Website")]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public string CompanyWebsite { get; set; }

    [DisplayName("Industry")]
    [Required]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public string Industry { get; set; }

    [DisplayName("Number of Employees")]
    [Required]
    public NumberOfEmployees NumberOfEmployees { get; set; }

    [DisplayName("Communication Preference")]
    [Required]
    public CommunicationPreference CommunicationPreference { get; set; }

    public Guid AddressId { get; set; }
    [Required]
    public AddressViewModel Address { get; set; }
}

網域聯系Object

    public class Contact
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public Salutations? Prefix { get; set; }

    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(100)]
    public string LastName { get; set; }

    [Required]
    [MaxLength(100)]
    public string JobTitle { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [MaxLength(100)]
    public string Email { get; set; }

    [Required]
    [MaxLength(100)]
    public string Phone { get; set; }

    [MaxLength(100)]
    public string PhoneExtension { get; set; }
}

基本聯系人查看 Model

    public class BaseContactViewModel
{
    public Guid Id { get; set; }

    [DisplayName("Primary Contact Prefix")]
    public virtual Salutations Prefix { get; set; }

    [DisplayName("Primary Contact First Name")]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string FirstName { get; set; }

    [DisplayName("Primary Contact Last Name")]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string LastName { get; set; }

    [DisplayName("Primary Contact Job Title")]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string JobTitle { get; set; }

    [DisplayName("Primary Contact Email Address")]
    [DataType(DataType.EmailAddress)]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string Email { get; set; }

    [DisplayName("Primary Contact Phone")]
    [DataType(DataType.PhoneNumber)]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string Phone { get; set; }

    [DisplayName("Primary Contact Extension")]
    [MinLength(3, ErrorMessage = "Your {0} must be at least {1} characters long")]
    [MaxLength(100, ErrorMessage = "Your {0} must be no more than {1} characters")]
    public virtual string PhoneExtension { get; set; }
}

二級聯系人查看 Model

public class SecondaryContactViewModel : BaseContactViewModel
{

    [DisplayName("Secondary Contact Prefix")]
    public override Salutations Prefix { get; set; }

    [DisplayName("Secondary Contact First Name")]
    public override string FirstName { get; set; }

    [DisplayName("Secondary Contact Last Name")]
    public override string LastName { get; set; }

    [DisplayName("Secondary Contact Job Title")]
    public override string JobTitle { get; set; }

    [DisplayName("Secondary Contact Email Address")]
    public override string Email { get; set; }

    [DisplayName("Secondary Contact Phone")]
    public override string Phone { get; set; }

    [DisplayName("Secondary Contact Extension")]
    public override string PhoneExtension { get; set; }

}

進行 EF 保存的方法

public async Task<bool> CreateBusinessAsync(BusinessViewModel businessViewModel)
    {
        try
        {
            // TODO: Move mapping to some common place?
            Mapper.CreateMap<BusinessViewModel, Business>();
            Mapper.CreateMap<BaseContactViewModel, Contact>();
            Mapper.CreateMap<AddressViewModel, Address>();


            Business business = Mapper.Map<Business>(businessViewModel);

            //TODO: See why EntityFramework isn't automatically putting in GUIDs
            business.Id = Guid.NewGuid();
            business.Address.Id = Guid.NewGuid();
            business.PrimaryContact.Id = Guid.NewGuid();


            // Attach the objects so they aren't saved as new entries
            db.States.Attach(business.Address.State);
            db.Countries.Attach(business.Address.Country);

            //TODO: See why entity framework isn't automatically saving records
            var bus = db.Businesses.Add(business);
            var primary = db.Contacts.Add(business.PrimaryContact);

            if (!String.IsNullOrEmpty(business.SecondaryContact.FirstName))
            {
                business.SecondaryContact.Id = Guid.NewGuid();
                db.Contacts.Add(business.SecondaryContact);
            }
            else
            {
                business.SecondaryContact = null;
            }


            var address = db.Addresses.Add(business.Address);

            int rowsAffected = await db.SaveChangesAsync();


            if (bus != null && rowsAffected > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            //TODO: Add exception logger
            string error = e.Message;

            return false;
        }

    }

請讓我知道查看任何其他課程是否有用。 謝謝。

我之前也遇到過類似的問題,而解決該問題的方法是從屬性中刪除外鍵數據注釋,並使用fluent-api。 使用fluent-api,我只是將關系的正確方面標記為可選。

您可以根據文檔將數據類型設置為可為空

public class Foo {
// ...... Some property
[ForeignKey("tagId")]
public ICollection<SomeModel>? data {get; set;}
}

這將使該屬性未經過驗證並返回經過驗證的結果。 使用 Model.IsValid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM