Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

C# Entity Framework Core 5.0.1 automatically adding foreign keys?

I'm having an issue with EF Core automatically adding foreign keys while I didn't ask for it.

So basically I'm using code first migrations in C# with SQL Server, some models and the basic context down below. But as you can see with my example models I'm adding a dependency from Event -> Item, one to many, what I want is many to many. What I think is happening is that EFCore is switching the foreign key dependencies around? I had linktables before like EventItems.

Am I required to use the linktables again or is there an other way to fix this?

Event model

namespace Models
{
    public class Event
    {
        [Required]
        public int Id { get; set; }
        public string Description { get; set; }
        [Required]
        public DateTime StartDate { get; set; }
        [Required]
        public DateTime EndDate { get; set; }
        public ICollection<Item> Rewards { get; set; }
    }
}

Event SQL

CREATE TABLE [dbo].[Events] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Description] NVARCHAR (MAX) NULL,
    [StartDate]   DATETIME2 (7)  NOT NULL,
    [EndDate]     DATETIME2 (7)  NOT NULL,
    CONSTRAINT [PK_Events] PRIMARY KEY CLUSTERED ([Id] ASC)
);

Item model

namespace Models
{
    public class Item
    {
        [Required]
        public int Id { get; set; }
        [Required]
        public string Path { get; set; }
    }
}

Item SQL

CREATE TABLE [dbo].[Items] (
    [Id]      INT            IDENTITY (1, 1) NOT NULL,
    [EventId] INT            NULL,
    [Path]    NVARCHAR (MAX) DEFAULT (N'') NOT NULL,
    [QuestId] INT            NULL,
    CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Items_Events_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[Events] ([Id])
);


GO
CREATE NONCLUSTERED INDEX [IX_Items_EventId]
    ON [dbo].[Items]([EventId] ASC);
question from:https://stackoverflow.com/questions/65601166/c-sharp-entity-framework-core-5-0-1-automatically-adding-foreign-keys

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...