First, create a ReadOnly Entity in Entity Framework.

ef-code-first entity-framework

Question

Is it possible to designate an object as read-only without giving it a key?

1
12
2/23/2012 2:50:11 PM

Accepted Answer

There are a few things you can do in Code First to enforce read-only. Use is the first step.AsNoTracking() whenever you ask.

var readOnlyPeople = (from p in context.People
                        where p.LastName == "Smith"
                        select p).AsNoTracking();

When you call Code First, it will know not to monitor changes to these things.SaveChanges() Any modifications made to these items won't be saved.

The second option is to change the state toUnchanged prior to dialingSaveChanges() .

context.Entry(person).State = EntityState.Unchanged;
context.SaveChanges();

This instructs Code First to disregard any changes made to that object.

There is no such thing as an entity that doesn't need a key. Although it "must uniquely identify an entity type instance inside an entity set," this may not always correspond to a primary key in the database.

12
2/23/2012 5:51:19 PM

Popular Answer

I made some entities that represent Views in EF6 using code-first, which clearly shouldn't be changed or saved. I used protected set attributes to stop changes to the Entity:

public class TransplantCenterView
{
    public string TransplantsThisYear { get; protected set; }
}

This property may still be set by Entity Framework, but other developers cannot inadvertently set it without a compile-time error. This is effective, but it would appear that fully banning tracking would be the wiser course of action.


I was able to update my code from: Thanks to Reggaeguitar's response, it seems there is a solution to this (please also vote up his response if the following is useful).

public class MyContext : DbContext
{
    public DbSet<TransplantCenterVeiw> TransplantCenterViews {get; set;}
}

To:

public class MyContext : DbContext
{
    //appears the DbSet is still needed to make Set<Entity>() work
    protected DbSet<TransplantCenterView> _transplantCenterViews {get; set;}
    //this .AsNoTracking() disables tracking for our DbSet.
    public DbQuery<TransplantCenterView> TransplantCenterViews {
        get { return Set<TransplantCenterView>().AsNoTracking(); }
    }
}

I'm not aware of any advantages or disadvantages of this, but the fact that my current code has continued to function flawlessly appears to be a gain.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow