Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6348083
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:21:06+00:00 2026-05-24T21:21:06+00:00

Hi I have an Invoice type like: public class Invoice : IEntity, IValidatableObject {

  • 0

Hi I have an Invoice type like:

public class Invoice : IEntity, IValidatableObject
    {
        public virtual int Id { get; set; }

        [Required(ErrorMessage = "Invoice Number is a required field.")]
        [Display(Name = "Invoice Number:")]
        public virtual string InvoiceNumber { get; set; }

        [Required(ErrorMessage = "Invoice Date is a required field.")]
        [Display(Name = "Invoice Date:")]
        [DataType(DataType.Date)]
        public DateTime? InvoiceDate { get; set; }

        [Required(ErrorMessage = "Organisation is a required field.")]
        [Display(Name = "Organisation:")]
        public int OrganisationId { get; set; }

        [Required(ErrorMessage = "Region is a required field.")]
        [Display(Name = "Region:")]
        public virtual int? AreaId { get; set; }

        [Required(ErrorMessage = "Total (Exc. GST) is a required field.")]
        [Display(Name = "Total (Exc. GST):")]
        public decimal? TotalExcludingGst { get; set; }

        [Required(ErrorMessage = "Total (Inc. GST) is a required field.")]
        [Display(Name = "Total (Inc. GST):")]
        public decimal? TotalIncludingGst { get; set; }
        public virtual string CreatedByUserName { get; set; }
        public virtual DateTime CreatedDateTime { get; set; }
        public virtual string LastModifiedByUserName { get; set; }
        public virtual DateTime? LastModifiedDateTime { get; set; }

        // Navigation properties
        public virtual Area Area { get; set; }
        public virtual Organisation Organisation { get; set; }

        public virtual ICollection<InvoiceLine> InvoiceLines { get; set; }

        #region IValidatableObject Members

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if ((TotalExcludingGst + (TotalExcludingGst * .15m)) != TotalIncludingGst) {
                yield return new ValidationResult("The total (exc. Gst) + Gst does not equal the total (inc. Gst).");
            }
        }

        #endregion

What I want to do is make sure on insert update that the combination of Organsation and InvoiceNumber is unique.

I’m considering something like:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
            {
                var repository = new Repository<Invoice>();

                if(!repositoy.CheckUnique(Id)) {
                    yield return new ValidationResult("The combination of Organisation and Invoice number is already in use");
                }
            }

Is this bad practise? To be instantiating the repository inside the model?

Is there a better way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T21:21:11+00:00Added an answer on May 24, 2026 at 9:21 pm

    Your solution is not work correctly in a multi user scenario. Because between checking whether an ID exists and saving changes another record maybe inserted with that same ID.

    You can create a Unique Constraint on your table. This is the safe way to ensure duplicates are not created.

    Current versions of EF does not model/support Unique Constraints. However what you can do is catch the specific exception and check the error message. Then show the errors

    try
    {
        //updation logic
        context.SaveChanges();
    }
    catch (System.Data.DataException de)
    {
        Exception innerException = de;
        while (innerException.InnerException != null)
        {
            innerException = innerException.InnerException;
        }
    
        if (innerException.Message.Contains("Unique_constraint_name"))
        {
            ModelState.AddModelError(string.Empty, "Error Message");
            return;
        }
    
        ModelState.AddModelError(string.Empty, "Error Message");
    
        return View();
    }
    

    If you are using ASP.NET Web forms you can check this answer

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Let's say I have a table like this: Customer,Invoice Type,Balance A,Good,50 A,Good,10 A,Bad,20 B,Good,20
I have this html <div> <input type=radio name=erp_report_type value=customerinvoice required> <label for=>Customer Invoice</label> <input
I have two classes Invoice and InvoiceItem. I would like Invoice to have a
I have a html file that has invoice details I would like to know
I have a query which produces a list of orders like this: Invoice Description
I have something like this: uses MSXML2_TLB; type TDocumentType = (dtOrder, dtInvoice, dtStatus, dtError);
We have scalar functions in our database for returning things like number of tasks
I have a simple Invoices class with a Number attribute that has to be
Suppose I have defined route like that, context.MapRoute( Preview, /preview/{id}/{type}, new { controller =
So i have all these links in html like this <a href=#ajax class=invlink competition_id=532>Gen

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.