C
C#

help

EF 6 - Creating entity with n-n

Rİrşat8/22/2022
PostDtoWrite_2 newpost = new PostDtoWrite_2();
newpost.Title = request.Title;
newpost.PostDescription = request.PostDescription;
newpost.LanguageId = request.LanguageId;
newpost.AccountId = request.AccountId;
newpost.PostTypeId = request.PostTypeId;
newpost.CoverImage = request.CoverImage;
newpost.PublishDate = DateTime.Now;
newpost.UpdateDate = DateTime.Now;
newpost.DeletedStatusId = 1;
newpost.PostTypeId = 1;
newpost.IsPublished = true;

try{
db.Posts.Add(mapper.Map<Post>(newpost));
await db.SaveChangesAsync();
} catch (Exception) {
return Results.StatusCode(580);
}

return Results.Ok();
PostDtoWrite_2 newpost = new PostDtoWrite_2();
newpost.Title = request.Title;
newpost.PostDescription = request.PostDescription;
newpost.LanguageId = request.LanguageId;
newpost.AccountId = request.AccountId;
newpost.PostTypeId = request.PostTypeId;
newpost.CoverImage = request.CoverImage;
newpost.PublishDate = DateTime.Now;
newpost.UpdateDate = DateTime.Now;
newpost.DeletedStatusId = 1;
newpost.PostTypeId = 1;
newpost.IsPublished = true;

try{
db.Posts.Add(mapper.Map<Post>(newpost));
await db.SaveChangesAsync();
} catch (Exception) {
return Results.StatusCode(580);
}

return Results.Ok();
I want to add "Tags" to this but there is no table for many to many in new versions of EF. public virtual ICollection<Tag> Tags { get; set; } I have this in my entity.
AAngius8/22/2022
Collection of A in B, collection of B in A All that's needed And get rid of any and all virtual in your models
Rİrşat8/22/2022
that's database first, i will delete the virtuals in dtos if there is one but i didn't understand a and b thing
AAngius8/22/2022
Example model names
Rİrşat8/22/2022
let me process it for a minute 😄
BVBrainiac V8/22/2022
First result on Google:
The second most common type of relationship is known as a Many To Many relationship. The following diagram shows how this appears in a database diagram. Each book can belong to many categories and each category can contain many books. This type of relationship is managed in a database through the use of a join table (also known among other things as a bridging, junction or linking table). This type of relationship is defined in code by the inclusion of collection properties in each of the entities:
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<Category> Categories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
public Author Author { get; set; }
public ICollection<Category> Categories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public ICollection<Book> Books { get; set; }
}
Rİrşat8/22/2022
yeah i already knew that though. But how do I add the Tags, I tried filling this collection but it gave an error also i use mapper, maybe there is something about it too
AAngius8/22/2022
book.Categories.Add(category);
await _ctx.SaveChangesAsync();
book.Categories.Add(category);
await _ctx.SaveChangesAsync();
Rİrşat8/22/2022
oh
AAngius8/22/2022
You need the actual model intances too, not mapped DTOs
Rİrşat8/22/2022
but i am using dto, is there an other way
AAngius8/22/2022
No
Rİrşat8/22/2022
let me try this first thanks btw
BVBrainiac V8/22/2022
You can see the flow like this: 1) Request comes from the client to get data: Model -> DTO 2) Client sends data that results in creating or updating something: DTO -> Model
Rİrşat8/22/2022
2) yes i am using mapper for that db.Posts.Add(mapper.Map<Post>(newpost)); db.Posts.Tags Doesn't exists i guess
AAngius8/22/2022
You don't have N-N set up, then
Rİrşat8/22/2022
public virtual ICollection<Tag> Tags { get; set; } it's there
AAngius8/22/2022
Ah You need a specific post Not all the posts
Rİrşat8/22/2022
i get the tags, i just can't create them in n n table
AAngius8/22/2022
Of course a DbSet of Posts won't contain a property Tags
var post = await _ctx.Posts.FindAsync(id);
post.Tags.Add(new Tag { ... });
await _ctx.SaveChangesAsync();
var post = await _ctx.Posts.FindAsync(id);
post.Tags.Add(new Tag { ... });
await _ctx.SaveChangesAsync();
Rİrşat8/22/2022
so i was thinking i could get the newly created post's id and then add the tags into the n n table. But simply there is no table in ef core 6 😄 let me check what you wrote
AAngius8/22/2022
You can add it to the newly-created post tho..?
Rİrşat8/22/2022
I have Post table, Tags table and Post_Tag table. post.Tags.Add(new Tag { ... }); I don't think that would work
AAngius8/22/2022
var post = new Post();
post.Tags = new List<Tag>(){
tag1, tag2, tag3
};
_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
var post = new Post();
post.Tags = new List<Tag>(){
tag1, tag2, tag3
};
_ctx.Posts.Add(post);
await _ctx.SaveChangesAsync();
Rİrşat8/22/2022
unless the "tags" here is the n n table here? oh i see but i tried this and got an error
AAngius8/22/2022
Nothing here is the join table
BVBrainiac V8/22/2022
I think you need to get away from that thinking in relations in databases for a moment
AAngius8/22/2022
There's zero join tables C#-side
BVBrainiac V8/22/2022
and switch to classes and objects
Rİrşat8/22/2022
okay okay i just saw that part. I am just saying i tried this filling the property thing. Catch was triggered, but let me check the error first should i create ICollection or List? as property
AAngius8/22/2022
List You cannot instantiate interfaces Ah, property? ICollection, List, either's fine
Rİrşat8/22/2022
alright is giving id only fine? Tags has an id and body.
AAngius8/22/2022
Ideally, you'd fetch the tags by ID from the database, but you can use an instance of Tag with ID alone, I think
Rİrşat8/22/2022
System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64.
AAngius8/22/2022
Ah, don't return database models from your API
Rİrşat8/22/2022
public List<TagDtoWrite_1>? Tags { get; set; } i am not returning it 😄
AAngius8/22/2022
Maybe because of the virtual? It enables lazy loading Dunno
Rİrşat8/22/2022
this error is completely irrelevant lol
AAngius8/22/2022
There's a cycle somewhere in what you return
Rİrşat8/22/2022
oh maybe it was a different error, i saw it in the terminal. It says this; Cannot insert explicit value for identity column in table 'Tag' when IDENTITY_INSERT is set to OFF. i am not trying to create a tag am i 😄
AAngius8/22/2022
Ah, when you're adding tags to the post, you do it with new Tag { Id = id } EF takes it as an attempt at creating a tag
Rİrşat8/22/2022
i used swagger for that "tags": [ { "id": 1 }, { "id": 2 }, { "id": 3 } ]
AAngius8/22/2022
So you either have to track those tags, to tell EF those are shims for existing ones, or you have to fetch the tags from the db
var tags = await _ctx.Tags
.Where(t => tagIds.Contains(t.Id))
.ToListAsync();

var post = new Post();
post.Tags = tags;

await _ctx.SaveChangesAsync();
var tags = await _ctx.Tags
.Where(t => tagIds.Contains(t.Id))
.ToListAsync();

var post = new Post();
post.Tags = tags;

await _ctx.SaveChangesAsync();
This would be the safest way Or... you can create an entity that represents the join table and configure it But I hear you use DB-first, so no clue how to do that I refuse to touch DB-first with a ten-foot pole
Rİrşat8/22/2022
it's so fun so far, why tho code first sounds messy
AAngius8/22/2022
It's the opposite, in my experience You write the code how you want it, define all the relationships as you need them, and never worry about the database At any and all times you work with C# There's no virtuals being generated, no BeanDto_5367s
Rİrşat8/22/2022
i see, maybe i learn code first when this is over foreach (var t in request.Tags) { newpost.Tags.Add(t); } This add method gives null error. Maybe I can't get the Tags from swagger at all 😄 I will return in 5 minutes
AAngius8/22/2022
Need to intialize the tags collection Or you can just do newpost.Tags = request.Tags
Rİrşat8/22/2022
yup it was already like that, i tried your way to see if there will be a difference and I noticed the null error while it's nullable, foreach gave an error like that welp, i can return the data and it gives me all the tags. I don't know why it says it's null @Angius I remembered your advice about creating an entity instead of the dto. I don't know why I insisted about creating dto and mapping it. I am already getting the data as dto so there is no security risk or anything 😄 It worked, thanks.

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
How can I make invisible Console NOT winformI have a project but i need to make invisible, but i can not to make it.namespace missing imports after copying class [Answered]Hi guys, I am struggling with a problem for a few weeks. So I have a ASP.NET Website project (Not wHow to combine null coascence and ternary operator?Hello, I have a string variable A. And I want to fill thid string A with value Yes if a bool is true.NET CORE 6 - Injecting IDbConnection... is it good practice?I have an api to build and using dapper - IDbConnection. Atm i have an instance of IDbConnection forUsing instructionHi, i would like to know when we are using the instruction "using like this : ```Java using (var coHow can I inject methodname into ILogger.Debug()-call without changing useage everywhere?Hi, I have some property I wish to inject into my log messages (Serilog). I found a way to obtain itTwo SwaggerUI for one SolutionHey guys, I have been looking around for a way to create two SwaggerUI for one project. I want to crMediatR - Can't create Responder [Answered]Hi all, I'm pretty sure this is an issue with registering services, but for some reason MediatR sayshow to exponential regression in c sharp?https://stackoverflow.com/questions/24336153/exponential-based-curve-fit-using-math-netASP.NET MVC Legacy Route HellSo I have a very old API that was originally written in MVC. this api manages projects where each pParadoxical initializers [Answered]Two classes. Class Character and Class Guild. Character has a field of Guild. Guild has an array ofMerge 2 csharp documents in visual studio [Answered]Hi, I just realized I have 2 identical files with different names and Im not sure which file has whupload video strategy in asp.netHi guys, I'm currently using ASP.NET for uploading image by passing IFormFile on http request But eRotational matrix transformationYeh look i've got a point, and it's got an offset for both X, and Y. From These offsets we have a roGenerate markdown docs [Answered]Can you please recommend me some some documentation generator, that is easy to use, ideally bit custWhat does 1..^0 mean when used in array.TitleHow to use Tuple in generic class?So I know you can use Tuple<Type, Func<object>> for example, but is there any way to just use (Type RichTextBox not paintingWhat can I do for richtextbox showing white spaces I have done double bufferedHow do you check if the port is open publicly for AspNetCore?I kept getting actively refusedGet word at mouse function doesn't work as I wantHi. I have this code: ```cs private string GetWordAtMousePosition(MouseEventArgs e) { var mouseP