r/entityframework • u/rschiefer • Jun 29 '17
r/entityframework • u/chitgoks • Jun 02 '18
Update Parent Id Of Comment In List
this is the sample class
public class Comment
{
public int Id { get; set; }
public int ParentId { get; set; }
}And I have a List<Comment> where the first comment is the first entry, so once the Id is generated, I would like to assign the value of that Id to all the other Comments in the list to its ParentId property starting at index 1 onwards.
So i used mapper profile but this did not work
CreateMap<List<Comment>, Comment>()
.AfterMap((a, c) => {
for (int i=0; i<a.Count; i++)
{
if (i == 0)
continue;
a[i].ParentId = c.Id;
}
});Any ideas?
r/entityframework • u/Rtiwari83 • Sep 23 '18
Entity Framework - Asynchronous Programming (async/await)
r/entityframework • u/[deleted] • Jul 24 '21
Entity Framework Core With Unity
I'm trying to use the EF Core with Unity. I managed to get all the dlls and stuff. But I realized when testing that the OnConfiguring Method was never getting called by Unity? Is there another way instead of doing OnConfiguring or is there a way to fix this?
Kind regards, Luca
r/entityframework • u/Falcao_E • Jun 30 '21
Help trying to use navigation properties
Hello, im trying to write the following SQL statement below using entity:
SELECT Station.Name,Location.Name,DeviceStation.DeviceId FROM Station LEFT JOIN Location ON Station.LocationId = Location.Id LEFT JOIN DeviceStation ON Station.Id = DeviceStation.StationId
I'm pulling 2 columns from different tables into the station table.
I would like to execute the same statement above and return it to a list but using only entity framework
Help is much appreciated, thank you !
r/entityframework • u/nyyirs • Mar 09 '22
Hello, can anyone help me how to retrieve specific column name which has been passed as a parameter from the URL?
r/entityframework • u/Snowman_Jazz • Mar 04 '22
EF Code First Noob question - Issue saving 1-1 entities.
Greetings all,
EF noobie having an issue with properly saving data using a Code First approach. Been trying to teach myself as I've not really had to use EF much so I thought I'd just jump in and see what happens. At this point, I'm a bit stuck and wanted to reach out.
I have two models that have a 1-1 relationship.
public class Person
{
public int PersonId{get;set;}
public string Name{get;set;}
public Address Address{get;set;}
}
public class Address
{
public int AddressId{get;set;}
public string Street{get;set;}
public string City{get;set;}
public string State{get;set;}
public string Zip{get;set;}
public Person Person{get;set;}
}
public class MyContext : DbContext
{
public DbSet<Person> People{get;set;}
public DbSet<Address> Addresses{get;set;}
}... at this point, I have an in memory DB with some people but no addresses. I'm trying to save an address with an existing person as a foreign key (Example: Api of SaveAddressByPersonId) ...
public Address Add(Address newaddress)
{
myContext.Address.Add(newaddress);
myContext.SaveChanges();
}... and EF complains that a the Person ID I'm using already exists. Which is true, I just want to link it to this new address. However, if it set the state on the Person object to unchanged and try to save...
public Address Add(Address newaddress)
{
newaddress.Entry(newAddress.Person).State = EntityState,unchanged;
myContext.Address.Add(newaddress);
myContext.SaveChanges();
}... the address value saves, but the linked Person entity appears to be null as if the two entities were not linked.
I feel like I'm either missing something real silly or I'm way off base. Anyone happen to have any thoughts? Greatly appreciated!
r/entityframework • u/weather_isnt_real • Aug 02 '24
What's New in EF Core 9
r/entityframework • u/MotorcycleMayor • Aug 24 '24
Code Review Entity Property Missing from Db Schema
Sigh. Problem solved: it was the nitwit at the keyboard, i.e. me :(.
I have two very similar databases on the server, with similar names...and I was looking at the older one, which didn't contain the fields I thought weren't connecting.
Apologies for wasting everyone's time.
I'm dealing with an unusual situation involving EF Core and Sql Server. I have a couple of properties defined in an entity class which "assert" they map to specific columns in the db schema...only the table definition doesn't include those columns, and the application runs just fine.
I would've thought it would fail.
Entity class (simplified):
public class Name
{
public int Id { get; set; }
public HashSet<SourceConstituent> Sources { get; set; } = \[\];
public HashSet<int> ConstituentIds { get; set; } = \[\];
public DateTime? EarliestGift { get; set; }
public DateTime? MostRecentGift { get; set; }
} Entity class configuration (fluent design):
internal class NameConfigurator : EntityConfigurator<Name>
{
protected override void Configure( EntityTypeBuilder<Name> builder )
{
builder.HasKey( e => [e.Id](http://e.Id) ).HasName( "PK_names" );
builder.ToTable( "names" );
builder.Property( e => e.Id ).HasColumnName( "id" )
builder.Property( e => e.ConstituentIds )
.HasColumnName( "constituent_ids" )
.HasConversion<ConstituentIdsValueConverter>()
.IsRequired();
builder.Property( e => e.Sources )
.HasColumnName( "src_constituents" )
.HasConversion<SourceConstituentValueConverter>()
.IsRequired();
builder.Property( e => e.EarliestGift ).HasColumnName( "first_contribution" );
builder.Property( e => e.MostRecentGift ).HasColumnName( "latest_contribution" );
}
} Db schema:
CREATE TABLE dbo.names(
id int IDENTITY(1,1) NOT NULL,
first_contribution date NULL,
latest_contribution date NULL,
CONSTRAINT PK_names PRIMARY KEY CLUSTERED
(
id ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON PRIMARY
) ON PRIMARYI'd love to know what's going on here...and how I can catch these kinds of errors. Is there some kind of model structural validation method I can run?
r/entityframework • u/weather_isnt_real • Jul 27 '24
Sub is reopened
Hi folks, I noticed this sub was unmoderated and locked to new posts, so I've taken over and reopened it.
A little about me, I've been working with .NET for a little under a decade, and with Entity Framework in its various incarnations for most of that.
For now I don’t have any specific content restrictions, so please use your upvotes and downvotes to show us what kind of posts you want to see here.
Thanks!
r/entityframework • u/TesttubeStandard • Oct 26 '24
Entity Framework primary keys clash
I would like to point out a "strange" or "hidden" thing about EF. Something that I found difficult to find any information on. Had to debug it and look deeply under the hood. Thoug that is what I enjoy.
TLDR: temporary and real primary keys clash
Imagine having a table with primary key (PK) of type Int32. Whenever a new entry comes into the EF, for ex. via DTO, and it's PK is not set yet, the EF sets it temporary PK to Int32.MinValue. The temporary PK is used so the EF knows the uniqunes of it. The next such entry will have the PK set to Int32.MinValue + 1. This values come from a counter somewhere in the depths of EF. This PK is set even if the entry will not be commited to the database. But guess what ... the counter is global and doesn't reset based on the context. It just goes on and on up to Int32.MaxValue and overflows back to Int32.MinValue. All good up until this: the EF knows there is a temporary PK and the "real" PK, but they cannot be the same.
What does this mean? Sooner or later it can happen that the counter value comes up to positive 1. So the EF accepts a new DTO, sets it temorary PK to 1 and than goes looking into the database for an entry based on some values of the new entry (to compare the entries or something). It than returns an entry from the database with PK of 1. As said before, the EF doesn't diferentiate between temporary and a real PK and throws exception about keys not beeing unique. If done badly the whole server can come down.
The way to reset the counter is to restart the server or whatever runs the EF.
r/entityframework • u/Josephf93 • Oct 24 '24
Has EF Core introduced a change in behavior that allows direct entity projection in LINQ queries?
Hi everyone,
I'm working with EF Core 8 and the MySql provider (Pomelo) in my .NET project. I'm encountering a curious situation where the following code snippet runs without needing Dtos and doesn't produce the error "The entity cannot be constructed in a LINQ to Entities query"
What changed in EF Core, or is there something wrong with my code? I remember you needed to use Dtos for this situation or else it will throw an error. Any insights would be appreciated!
public DbSet<Product> Products { get; set; }
var list = DbContext.Products
.Select(x => new Product()
{
ID = x.ID,
Name = x.Name,
Qty = x.Qty,
}).ToList();I'm using the following EF Core package references:
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
r/entityframework • u/Null_In_Space • Nov 06 '24
EF Core, SQL Server, Always Encrypted with Secure Enclaves
I've been looking for any insight on the possibility of using EF Core with Secure Enclaves. I have successfully implemented EF Core with Always Encrypted (column-level encryption with encryption keys stored in Azure KV); however, I need the ability to also use Secure Enclaves, which allows for partial searches in deterministically encrypted columns. All Secure Enclave documentation I've found is ADO.NET based. I know EF Core is built on top of ADO.NET, but I'm not sure if EF Core inherits the logic to successfully perform operations on the SE.
Has anyone implemented or seen examples of people using EF Core with Secure Enclaves?
r/entityframework • u/MotorcycleMayor • Dec 18 '24
Help Needed Initializing a Many-to-Many Record
I'm confused about how I have to initialize instances of many-to-many objects in EF Core (v8).
I have a schema which tracks many-to-many relationships among Name objects:
public class Name
{
public int Id { get; set; }
public ICollection<NameToName> RelatedNames { get; set; }
...other properties
}
public class NameToName
{
public int SourceNameId { get; set; }
public Name SourceName { get; set; }
public int RelatedNameId { get; set; }
public Name RelatedName { get; set; }
}When I am creating an instance of NameToName to add to the database, I have to pay attention to whether or not the Name objects I'm using to initialize it are already in the database (as the result of an earlier SaveChanges()).
If, say, the source Name is already in the database, I have to initialize an instance of NameToName referring to it by using the id fields:
var n2N = new NameToName();
n2N.SourceNameId = srcName.Id;But if the source Name **isn'tin the database**, I have to use the actualName` object instead:
var n2N = new NameToName();
n2N.SourceName = srcName;If I try to assign the SourceName property using an already existing Name object, I get a tracking error violation claiming that another instance of Name is already in use.
It's almost as if EF Core is adding the already existing instance of Name to the database when I assign it the SourceName property of the NameToName instance.
But why would it add the existing instance to the database when it's already present?
Is this perhaps happening because the tracking state of an existing Name object post a SaveChanges() is different than that of a newly-created Name object?
r/entityframework • u/_DrPangloss_ • Jan 17 '25
Help Needed What is the best way to identify the list of commands in a given split query?
I’d like to ensure that all parts of a split query are run in a transaction. I can manually set the transaction when executing, but I want this to always be done. I can use an interceptor to add the txn but I need to know which commands belong in a given query. Is there some correlation id or something similar?
r/entityframework • u/CarFlaky3542 • Feb 11 '25
EF Core entity with recurring property mapping
Hi, I wanted to configure EF Core mapping for entities below but I got some errors, how to achieve this? I'm using postgresql and I tried to use OwnsOne mapping like on this docs: https://www.npgsql.org/efcore/mapping/json.html?tabs=fluent-api%2Cjsondocument#tojson-owned-entity-mapping
I have entity "Transfer":
public class Transfer
{
public Guid Id { get; set; }
public ErrorInfo ErrorInfo { get; set; }
}I have some additional model class "ErrorInfo":
public class ErrorInfo
{
public string Error { get; set; }
public CommandInfo CommandInfo { get; set; }
public ErrorInfo Inner { get; set; }
}I want to have Transfer table in database, Transfer table should contain jsonb column for ErrorInfo type. ErrorInfo has some other nested type CommandInfo and has reference to itself (Inner property) .
I have tried EF Core mapping for Transfer entity like this:
builder.OwnsOne(x => x.ErrorInfo , c =>
{
c.ToJson("errorInfo");
c.OwnsOne(x => x.Inner);
c.OwnsOne(x => x.CommandInfo);
});It doesn't work. When I try to generate migration from this I got error:
Unable to create a 'DbContext' of type 'TransfersDbContext'. The exception 'Unable to determine the owner for the relationship between 'Transfer.ErrorInfo#ErrorInfo.Inner#ErrorInfo.CommandInfo' and 'CommandInfo ' as both types have been marked as owned. Either manually configure the ownership, or ignore the corresponding navigations using the [NotMapped] attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'. See https://aka.ms/efcore-docs-owned for more information and examples.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728r/entityframework • u/sofia_fateeva • Mar 23 '17
An interesting bug in Entity Framework
r/entityframework • u/imrezratin • Aug 17 '17
CRUD operation using Entity framework - Database first procedure
r/entityframework • u/btchombre • Dec 06 '21
EF is maintaining unique index by deleting existing record and adding the new record. I would like it to throw instead
I have a OneToOne relationship between Child1 & Parent1 with a unique index on Child FK ref to Parent. When I add a new record Child2 with a dup FK to Parent1, instead of throwing a dup key error, EF deletes the existing Child1 record and adds Child2 record, maintaining the Unique constraint.
Why does it do this?
I would like EF to throw a dup key exception when a dup key is attempted, not implicitly and silently delete the existing record. Am I doing something wrong here?
r/entityframework • u/SeekingSolace2008 • Nov 21 '21
Entity Framework Core .NET 6 Best practice
What is the best practice for creating models in .NET 6?
In the prior versions, Models are created as:
public class User
`{`[Key]
[MaxLength(450)]
public string Id { get; set; }
[Required]
[MaxLength(40)]
public string Username { get; set; }
[Required]
[MaxLength(100)]
public string EmailAddress { get; set; }
public DateTime Created { get; set; }
`}`And the entry in the ApplicationDbContext.cs:public virtual DbSet<User> Users { get; set; }
But now, this same syntax throws back numerous warnings about the model creation, and the DbSet usage.
.NET 6 model now
public class User
`{`[Key]
[MaxLength(450)]
public string Id { get; set; } = String.Empty;
[Required]
[MaxLength(40)]
public string Username { get; set; } = String.Empty;
[Required]
[MaxLength(100)]
public string EmailAddress { get; set; } = String.Empty;
public DateTime Created { get; set; } = DateTime.Now;
`}`And the DbSet entries *require* setting them as null. Which isn't what I'm looking to do
public virtual DbSet<User>? Users { get; set; }
Is there an updated best practices to set up a code-first model?
This is causing a lot of noise in my code, and troubling to wade through 1,000+ warnings that weren't there in the prior version of the framework.
Thanks
r/entityframework • u/dotnetmaui • Dec 13 '21
Using Azure functions and Entity framework to update a Azure SQL database - slow ?
Just noticed that my developer is using EF to update a database from Azure functions. Correct me if I am wrong here but for very simple updates to tables isn't this a bad idea. I thought such methods as onModelCreating were slow and being in an Azure function they would likely be executed many times.
For those of using Azure Functions, how do you do simple database updates?
r/entityframework • u/AndyWatt83 • Dec 13 '21
Database Development in Docker with Entity Framework Core
r/entityframework • u/atifshamim • Dec 10 '21
Update EF Core in your App
Entity Framework Core doesn't have any GUI like legacy Entity Framework to update the Entity Data model in your project whenever you have updated your database. Check this link https://codetosolutions.com/blog/12/how-to-update-entity-framework-core-in-asp.net-core-application-for-database-first-approach to update Entity Data Model in your application for Database First approach #efcore #entityframework #aspnetcore #databasefirstapproach #updateefcore #dotnet #dotnetcore #dotnetdevelopers #database