0

I'm looking for a way to create a read only (or immutable) version of an entity that I will be using as a reference object. e.g.

class Order
{
   public int OrderId {get; private set;}

   public virtual Product ProductOrdered{get;set;}
   public int ProductId {get;set;}

   public int Quantity{get;set;}
}

class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }
}

in the example above Product is supposed to be used as a reference data. i.e. Product should not be modified by code using product as a reference in the Order.

Now, I realize one way to enforce that is to make all the setters as private and no one would be able to change Product...

class ProductReadOnly
{
    public int ProductId { get; private set; }
    public string Name { get; private set; }
    public string Category { get; private set; }
}

but somewhere in my app i'll like the admins to be able to create/modify products. So, I could use the class Product (with public setters)

Now the questions are (assuming I'm able to map Product & ProductReadOnly to the product table using Table attribute)

  1. will i be able to use ProductReadOnly as a navigation property in the Order class?
  2. Can I load Product & ProductReadOnly (same product) in the same data context?
  3. is there an easier way to do it (Detached object?)
  4. any issues with this approach?
abatishchev
  • 98,240
  • 88
  • 296
  • 433
skywqr
  • 36
  • 6

1 Answers1

2

No need to keep two entities like your solution.You can override SaveChanges in your context and disable/enable edit/add for products like this.

    public override int SaveChanges()
    {
      if(currentUserIsNotAnAdmin){
      var entries= ObjectStateManager.GetObjectStateEntries(EntityState.Added |   
   EntityState.Modified).OfType<Product>() ;
        foreach(entry in entries){//or throw an error here
          this.Entry(entry).State=System.Data.EntityState.Unchanged
        }
      }
        return base.SaveChanges();
    }

here I have disabled saving changes for the product entity if the current user is not a admin. Or else you can throw an error if there is any entry modified/added of type Product

Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
  • This looks correct, but feels like the wrong way to solve the problem. – ta.speot.is Mar 29 '13 at 03:35
  • Thanks. Instead of depending on the logged in user I'd like this to be based on the functionality of the application. I'm trying to figure out a design based solution that can be applied across the board. – skywqr Mar 29 '13 at 11:29