logo
Tags down

shadow

Problem with EF-Core Code first throwing error because of backing field


By : tamizh
Date : October 14 2020, 02:21 PM
I wish did fix the issue. Here is the case. By EF Core terminology these are not properties, but navigation properties, so they cannot be configured with Property fluent API (and in general are not returned by any metadata/entry method having Property / Properties in the name).
Instead, they are configured through relationship related fluent APIs. The problem with mapping the backing field though is that there is no natural fluent API for that similar to "properties", so you have to use directly the metadata.
code :
modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step1)
    .WithMany()
    .Metadata.DependentToPrincipal.SetField("_step1");

modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step2)
    .WithMany()
    .Metadata.DependentToPrincipal.SetField("_step2");
modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step1)
    .WithMany()
    .Metadata.DependentToPrincipal.SetPropertyAccessMode(PropertyAccessMode.Field);

modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step2)
    .WithMany()
    .Metadata.DependentToPrincipal.SetPropertyAccessMode(PropertyAccessMode.Field);
modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step1);

modelBuilder.Entity<Workflow>()
    .HasOne(e => e.Step2);


Share : facebook icon twitter icon

What's the code behind a C# backing field in a auto implemented get; set;?


By : davidholcer
Date : March 29 2020, 07:55 AM
hop of those help? It's wrong; your code is doing much more than just getting and setting a string.
An auto-implemented string property ModifiedBy simply expands to the following equivalent manually-implemented property:
code :
// Key difference: the backing field of an automatic property
// is not accessible by your own code
private string m_modifiedBy;

public string ModifiedBy {
    get { return m_modifiedBy; }
    set { m_modifiedBy = value; }
}

Why is EF code first throwing model backing context exception? Using 4.0.3


By : Surya Setty
Date : March 29 2020, 07:55 AM
may help you . Heres the exception: , For EF runtime version 4.0.3 / version 4.0
code :
public class ScannerContext : DbContext
{
    public ScannerContext()
        : base("LabDatabase") { }

    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        Database.SetInitializer<ScannerContext>(null); // <--- This is what i needed

        ...

        base.OnModelCreating(modelBuilder);

    }
}

EntityFramework Core Computed Property Error: InvalidOperation No Backing field


By : user3109093
Date : March 29 2020, 07:55 AM
help you fix your problem Decided to circle back to this as I eventually found the resolution to the very similar problem I was having - the problem of a field in an entity class requiring a conversion. Mine was slightly different in that my backing field was a different type (an enum), with the public getter and setter converting to and from string.
TLDR - the the fix for the original problem should be to change AgeYears & AgeMonths from properties with getters, to simple methods e.g. public int GetAgeYears() & public int GetAgeMonths();
code :
set
{
    // Required by EF
}
private Status _status;

public string Status
{
    get { return _status; }
    private set {
        _status = ParseRag(value);
    }
}
public static RagStatus ParseRag(string value)
{
    Status rag;
    Enum.TryParse(value, out rag);
    return rag;
}
private Status _status;
public Status Status
{
    get { return _status; }
}
public string GetStatus()
{
    return Status.ToString();
}
public static class EnumHelper
{
    public static T ConvertToEnum<T>(this string value)
    {
        if (Enum.IsDefined(typeof(T), value)) {
            return (T)Enum.Parse(typeof(T), value);
        }
        else {
            throw new ArgumentException($"{value} is not of the expected Enum");
        }
    }

    public static bool IsEnum<T>(this string value)
    {
        if (Enum.IsDefined(typeof(T), value)) {
            return true;
        }
        else {
            return false;
        }
    }
}
entity.Property(e => e.Status)
    .HasColumnName("Status")
    .HasMaxLength(255)
    .IsUnicode(false)
    .HasConversion(
        v => v.ToString(),
        v => v.ConvertToEnum<Status>());

my code is throwing a indent error and i cant find the problem


By : jmat
Date : March 29 2020, 07:55 AM
hope this fix your issue I'm not sure about your indentation but the correct form of try-else IMO is try-except-else. Like this:
code :
try:
    ...
except Exception:
    ...
else:
    ...

Make EF Core 2 work with a getter only property without a backing field


By : Klim Schukin
Date : March 29 2020, 07:55 AM
With these it helps What you are asking is possible in general with EF Core 2.1 introduced Entity types with constructors with parameters feature. You don't need the empty constructor anymore - EF Core will be able to use the constructor with Guid id parameter.
However there are two limitations which apply to your Id property. First, it's a read-only property (hence is backed by readonly field which can be set only from a constructor). The equivalent in your explicit backing field example would be if you define it as private readonly Guid _id;. Then the sample configuration WON'T work.
code :
modelBuilder.Entity<Foo>()
    .Property(e => e.Id)
    .ValueGeneratedNever();
Related Posts Related Posts :
  • Return type as IEnumerable instead of just List?
  • How to get transient DbContext in ASP.NET MVC Core?
  • Grouping data in ViewModel ASP.NET MVC & C#
  • Using a parameter's property in an ArgumentException
  • EF Unable to determine the relationship represented by navigation property
  • Moq: running flows with FluentValidation
  • "Reset" switch statement after value is equal
  • What does the question mark followed by a period mean if it is next to a variable?
  • How to P/Invoke os_log?
  • Deep copy object properties (including those with private setter) to another object of the same type
  • How to generate new back colour if two object's back colour match?
  • How to calculate percentage of value inside arbitrary range?
  • typeof(T) when T is dynamically created is null?
  • Run the application faster with Run Query at Start
  • c# code returns System.Data.DataSet instead of Data itself?
  • Compile binaries to multiple versions of .NET Framework using Bazel
  • How to hide table rows in a DataList if column data returns null from SQL Server
  • Exception handling with lambda/linq statements
  • Creating a meal Cost calculator C#
  • Plugin Failing on D365 v9 Online when I just have tracers to test execution
  • ASP.NET MVC Deleting row from one table after copying it to another table
  • Error VSSDK1001: Unable to find Microsoft.VisualStudio.CommandTable.VSCTCompiler type
  • Trying to fetch a string from another form but i get string value null
  • Entity Framework equivalent of the following query?
  • How do I get projection of one list to another with Linq?
  • I am using Alpha Vantage API to try and pull daily stock info. I am really new to using APIs and don't know what I am do
  • Get column names and types out of XMLSchema
  • Unable to read large log file with MemoryMappedViewStream
  • looping through file to add to datagridview
  • C# How do I ask for Admin, without "forcing" him
  • System.ComponentModel.Win32Exception: "The system cannot find the file specified"
  • How to add list to SQL query?
  • Visitor pattern: Number arithmetics based on input
  • How to remove a single DataLabel from a Chart made with EPPlus and C#
  • GameObjects will not load after game Restarts
  • Getting all dates between two dates using datepickers and Entity Framework 6
  • What should TResult be when using public async Task to return json response from API HTTP Post
  • Automapper Sub Property Mapping
  • reading a json file exception "Unhandled Exception: System.TypeInitializationException: The type initializer for &q
  • How to get MacOS username in .NET Core console app?
  • How can I extract the first word of every line of a text file in C#
  • HttpClient isn't using Client Certificate for Mutual TLS Auth
  • How do I make a generic dictionary for multiple types implementing the same interface?
  • C# Form add controls on runtime
  • C# - program about while loop
  • Accessing variables in other Windows Form class C#
  • How to display tooltip / context menu from Run object in (wpf) RichTextBox
  • How to get a 0 before a datetime day when the day is below 10 in C#
  • Nothing shows when I tried to fill Combobox with .csv filenames
  • RSA Crypto: Is it require to store keypair after geneating first time
  • potential problems with c# with windows 7 due to .net versions
  • ASP.NET Core 2.1 RedirectToAction appends TempData to url
  • Random Number Generator using C#
  • Mixing MockVerify and FluentAssertions.Should() in C#
  • IdentityServer4 and Web Api in one project fails to authenticate
  • WebApi Core project debug is hanging on await client.GetAsync
  • Why can't I load System.Security.Cryptography.ProtectedData when it's on the same directory as the executable
  • Regular expression repeated sequence of characters
  • How to check all checkbox by pressing one?
  • Is it possible to use Plotly.js in a C# Winforms WebBrowser component?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org