You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We have a sample table like below. Is it possible to create the following tables with migration? Is there a command that all indexes and constraints will be automatic? Isn't it very unnecessary to define them one by one for initial?
[MigrationVersion("2024-05-15 14:00:00", "Initial")]
internal class Initial : Migration
{
if (!Schema.Table(nameof(Post)).Exists())
{
Create.Table(nameof(Post)).Automatic(Post);
}
if (!Schema.Table(nameof(Tag)).Exists())
{
Create.Table(nameof(Tag)).Automatic(Tag);
}
if (!Schema.Table(nameof(PostTag)).Exists())
{
Create.Table(nameof(PostTag)).Automatic(Post);
}
}
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
namespace Domain
{
public class Post
{
public int Id { get; set; }
[StringLength(400)]
[Required]
public string Name { get; set; }
public List<PostTag> PostTags { get; }
public List<Tag> Tags { get; }
}
public class Tag
{
public int Id { get; set; }
[StringLength(400)]
[Required]
public string Name { get; set; }
public List<PostTag> PostTags { get; }
public List<Post> Posts { get; }
}
internal class PostTagMap : IEntityTypeConfiguration<PostTag>
{
public void Configure(EntityTypeBuilder<PostTag> builder)
{
builder
.HasOne(a => a.Tag)
.WithMany(a => a.PostTags)
.HasForeignKey(c => c.PostsId)
.OnDelete(DeleteBehavior.ClientSetNull);
builder
.HasOne(a => a.Tag)
.WithMany(a => a.PostTags)
.HasForeignKey(c => c.TagsId)
.OnDelete(DeleteBehavior.ClientSetNull);
}
}
[Index(nameof(PostsId), Name = "IX_PostTag_PostsId")]
[Index(nameof(TagsId), Name = "IX_PostTag_PostsId")]
[Index(nameof(DisplayOrder), Name = "IX_PostTag_PostsId")]
[Index(nameof(PostsId), nameof(TagsId), IsUnique = true, Name = "IX_PostTag_PostsId_TagsId")]
public class PostTag
{
public int Id { get; set; }
public int DisplayOrder { get; set; }
public int PostsId { get; set; }
public int TagsId { get; set; }
public Post Post { get; set; } = null!;
public Tag Tag { get; set; } = null!;
}
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Hi,
We have a sample table like below. Is it possible to create the following tables with migration? Is there a command that all indexes and constraints will be automatic? Isn't it very unnecessary to define them one by one for initial?
Beta Was this translation helpful? Give feedback.
All reactions