0

I am using Entity Framework to create a simple banking application for learning purposes. I don't understand how it decides which properties will become nullable and which become non nullable columns in the database.

For example this

model

public class Transaction
    {
        public int Id { get; set; }
        public Account From { get; set; }
        public Account To { get; set; }

        [DataType(DataType.Currency)]
        public decimal Amount { get; set; }
        public String Currency { get; set; }
        public DateTime Timestamp { get; set; }
    }

generates the following

SQL

enter image description here

CREATE TABLE [dbo].[Transactions] (
    [Id]        INT             IDENTITY (1, 1) NOT NULL,
    [Amount]    DECIMAL (18, 2) NOT NULL,
    [Currency]  NVARCHAR (MAX)  NULL,
    [FromId]    INT             NULL,
    [Timestamp] DATETIME2 (7)   NOT NULL,
    [ToId]      INT             NULL,
    CONSTRAINT [PK_Transactions] PRIMARY KEY CLUSTERED ([Id] ASC),
    CONSTRAINT [FK_Transactions_Accounts_FromId] FOREIGN KEY ([FromId]) REFERENCES [dbo].[Accounts] ([Id]),
    CONSTRAINT [FK_Transactions_Accounts_ToId] FOREIGN KEY ([ToId]) REFERENCES [dbo].[Accounts] ([Id])
);


GO
CREATE NONCLUSTERED INDEX [IX_Transactions_FromId]
    ON [dbo].[Transactions]([FromId] ASC);


GO
CREATE NONCLUSTERED INDEX [IX_Transactions_ToId]
    ON [dbo].[Transactions]([ToId] ASC);

Question

Why is Currency nullable but not Amount? And what about the foreign keys FromId and ToId?

Appendix

In case it is relevant, here is the Account class referenced by the Transaction class.

public class Account
    {
        public int Id { get; set; }
        public int UserId { get; set; }    
        public User User { get; set; }

        [InverseProperty("From")]
        public ICollection<Transaction> TransactionsSend { get; set; }
        [InverseProperty("To")]
        public ICollection<Transaction> TransactionsReceived { get; set; }

        public decimal Balance { get; set; }
    }
  • Possible duplicate of [What does "DateTime?" mean in C#?](https://stackoverflow.com/questions/109859/what-does-datetime-mean-in-c) – H H Aug 04 '18 at 18:06

1 Answers1

1

There is a set of conventions at work here. You can fine-tune everything but the basic rules are clear and simple:

Why is Currency nullable but not Amount? And what about the foreign keys FromId and ToId?

Amount is a value-type. The C# property can't be null When you change it to decimal? the column will be nullable too.
Currency is a reference-type (string ). The From and To properties are references too. References will map to ALLOW-NULL unless you mark them as [Required]

And DateTime is also a value-type.

H H
  • 263,252
  • 30
  • 330
  • 514