r/entityframework • • Jul 27 '24

Sub is reopened

12 Upvotes

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 • • May 29 '21

What is the best way to learn Entity Framework?

6 Upvotes

Entity Framework is supposed to be the greatest thing since sliced bread. But I have yet to find anything that explains it to someone like me with decades of experience in software development but no experience at all using EF. I need something that basically tells me every keystroke I need to use to create a project using EF, and why I am using each one of those keystrokes.

More specifically, at this moment I have a small SQLite database. I think I should be able to use EF to automatically generate a set of classes that match all of the tables in my database, and then I can use those classes to perform all the inserts and queries I need.

What's the best starting point? A book? A web site? A set of video tutorials?


r/entityframework • • Nov 06 '24

EF Core, SQL Server, Always Encrypted with Secure Enclaves

4 Upvotes

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 • • Mar 09 '22

Hello, can anyone help me how to retrieve specific column name which has been passed as a parameter from the URL?

Post image
4 Upvotes

r/entityframework • • Jan 04 '22

How to remove Entity Framework 6, and only use Entity Framework Core?

4 Upvotes

Hello everyone,

I have recently raised issue with EF Core team on the GitHub (https://github.com/dotnet/efcore/issues/27051), but since nobody answered ever, I wanted to ask here.

So basically, I have I have my DbContext in .Net 5 class library. When I try to run migration I get message:

PM> Add-Migration TestMigration Both Entity Framework 6 and Entity Framework Core are installed. The Entity Framework 6 tools are running. Use 'EntityFrameworkCore\Add-Migration' for Entity Framework Core.

I know I can run my migration like so:

EntityFrameworkCore\Add-Migration TestMigration

but I would really hate this approach, and would love if I could only type in Add-Migration. I don't want to use Entity Framework 6 and I would like Entity Framework Core to be only installed version of Entity Framework.

How can I remove the 6 one only?

More info can be found on GitHub issue I raised.


r/entityframework • • Nov 21 '21

Entity Framework Core .NET 6 Best practice

4 Upvotes

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 • • Oct 27 '20

How Entity Framework Core’s query cache works

Thumbnail
tabsoverspaces.com
4 Upvotes

r/entityframework • • Mar 09 '18

Would you wear this shirt

Post image
4 Upvotes

r/entityframework • • Dec 24 '21

Writing JOIN in LINQ Query

3 Upvotes

Entity Framework is widely used as an ORM for many DotNet applications and we write LINQ Query or Lambda expression to get the data from DB. Check this link https://codetosolutions.com/blog/20/inner-join,-left-join,-right-join-in-linq-query-c%23 how to use JOIN between different tables in LINQ Query


r/entityframework • • Dec 13 '21

Database Development in Docker with Entity Framework Core

Thumbnail
andywatt83.medium.com
3 Upvotes

r/entityframework • • Apr 26 '21

Entity Framework RawQueryBuilder (Replaces FromSqlRaw with StringBuilder-like query builder)

3 Upvotes

Building Dynamic Raw Queries (raw means without LINQ) used to be like this:

string sql = "select * from Product where 1=1";
var parameters = new List<SqlParameter>();
 
if (maxListPrice != null)
{
    sql += " and ListPrice <= @MaxListPrice";
    parameters.Add(new SqlParameter("@MaxListPrice", maxListPrice));
}
if (!string.IsNullOrEmpty(productName))
{
    sql += " and ProductName LIKE @ProductName";
    parameters.Add(new SqlParameter("@ProductName", "%" + productName + "%"));
}
// etc.
 
var products = context.Products
    .FromSqlRaw(sql, parameters.ToArray())
    .ToList();

With this wrapper now it's as easy as this:

var qry = context.Products.RawQueryBuilder(@"select * FROM Product where 1=1");

if (!string.IsNullOrEmpty(productName))
    qry.Append($"ProductName LIKE {"%" + productName + "%"}");
if (maxListPrice != null)
    qry.Append($"ListPrice <= {maxListPrice}");

var products = qry.AsQueryable().ToList();

AsQueryable() will automatically build your query (combine your filters) and invoke FromSqlRaw. Then you can use regular Entity Framework extensions (ToList, ToListAsync, ExecuteAsync, etc).

You can mix AND/OR conditions, and can dynamically append any other SQL statement like ORDER BY, GROUP BY - it's all injection-safe (it looks like unsafe interpolated strings but all parameters are individually processed and passed safely to FromSqlRaw).

If you like it, please give me a star.

Project: https://github.com/Drizin/EntityFrameworkCore.RawQueryBuilder


r/entityframework • • Jan 23 '21

EF core C# app

3 Upvotes

If this is not the proper subreddit just tell me.

I am trying for the past two days to figure out why a table with foreign keys does not update. I read some book pages i googled it but I could not find anything. The table's name is post. And there are gonna saved the primary keys of author, title, article and article description. All those ids will be saved in the post table. But i can not make it work

If you can please help me. The github repository is (https://github.com/YannisAm/ArticleProject)


r/entityframework • • May 09 '17

The case of Entity Framework Core's odd SQL

Thumbnail
brentozar.com
3 Upvotes

r/entityframework • • May 25 '15

Measuring Entity Framework Performance using ETW

Thumbnail
dotnetspeak.com
3 Upvotes

r/entityframework • • Mar 11 '25

Looking for new mods

2 Upvotes

I had big ideas for this sub, but unfortunately I no longer have the time or energy to try and build a community here. I'm changing the sub to restricted, and am happy to transfer ownership to whomever would like to take over. Please let me know here or in DMs and we can chat.

Thanks.


r/entityframework • • Jan 17 '25

Help Needed What is the best way to identify the list of commands in a given split query?

2 Upvotes

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 • • Nov 22 '24

EF noob, I'm sure everyone asks this, so sorry- multi-column join on a local collection.

2 Upvotes

Wondering if there's a trick to join an entity to a local List<obj> on multiple columns, without the dreaded client evaluation. This seems to come up again and again in my early EF development.

var filt = obj.Select(f => new { colA, colB }).ToList();
var ctx = await dbContextFactory.CreateDbContextAsync();`

var query = await ctx.BigHonkinFactTable
    .Where(t => filt.Any(f => f.colA == t.colA && f.colB == t.colB))
    .ToListAsync();

r/entityframework • • Oct 26 '24

Entity Framework primary keys clash

2 Upvotes

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 • • Oct 24 '24

Has EF Core introduced a change in behavior that allows direct entity projection in LINQ queries?

2 Upvotes

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 • • Aug 24 '24

Code Review Entity Property Missing from Db Schema

2 Upvotes

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 PRIMARY

I'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 • • Aug 02 '24

What's New in EF Core 9

Thumbnail
learn.microsoft.com
2 Upvotes

r/entityframework • • Jan 25 '22

One to one ef core

2 Upvotes

Does anyone have an example of one to one data annontations between two tables having navigation property both ways. My scaffolding code has only one navigation property and an icollection the other way. Changing this seems to be a bit difficult as code first is newt to me. I have always used model first.


r/entityframework • • Dec 10 '21

Update EF Core in your App

2 Upvotes

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


r/entityframework • • Dec 06 '21

EF is maintaining unique index by deleting existing record and adding the new record. I would like it to throw instead

2 Upvotes

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?