Nicolas
Nicolas

Reputation: 2376

Make reference table data read-only - EF Core

I have a table (Commodity) which has a one-to-one relationship with another table (CommodityMaterial), in my GET endpoint the Commodity returns it's own columns and also the columns (and values) of the referenced table which works perfectly. However, in the POST operation of the endpoint, a user should not be able to POST data of the reference table (CommodityMaterial), how can this be achieved? I used to disable this by using a DataContract, however, because I need the columns for my GET operator, this is not an option.

I already tried, following this post: https://csharp.christiannagel.com/2016/11/07/efcorefields/, removing the SET on the reference table and making a backing field but this does not seem to work (error that the backing field is read-only).

I also tried setting the SET to protected, but this is not working.

So the question is, how to make the reference table read-only (only available for my GET endpoint and not my POST endpoint).

The Commodity POCO class:

[DataContract]
    public class Commodity
    {
        public Commodity()
        {

        }

        public Commodity(CommodityMaterial commodityMaterial)
        {
            CommodityMaterial = commodityMaterial;
        }

        [DataMember]
        public long CommodityID { get; set; }

        [DataMember]
        public long CommodityMaterialID { get; set; }

        [DataMember]
        public decimal? SpecficWeight { get; set; }

        [DataMember]
        public CommodityMaterial CommodityMaterial { get; }
    }

Fluent part:

modelBuilder.Entity<Commodity>(entity =>
            {
                entity.Property(e => e.CommodityID)
                    .HasColumnName("CommodityID")
                    .ValueGeneratedOnAdd();

                entity.Property(e => e.CommodityMaterialID)
                    .HasColumnName("CommodityMaterialID");

                entity.Property(e => e.SpecficWeight)
                    .HasColumnName("SpecficWeight")
                    .HasColumnType("decimal(18, 2)");

                entity.HasOne(a => a.CommodityMaterial)
                    .WithOne(b => b.Commodity)
                    .HasForeignKey<Commodity>(b => b.CommodityMaterialID);

            });

Upvotes: 1

Views: 1031

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239200

The parameters your action accepts should represent what your action does/is allowed to do. If a client should not be able to update a related entity, then the class you bind the request body to, should not have that entity available. Use a view model, essentially:

public class CommodityRequest
{
    // all properties you want editable
    // exclude `CommodityMaterial` obviously
}

Then:

public IActionResult Update(CommodityRequest model)

Upvotes: 3

Related Questions