sapiens/SqlFu

Best practice for handling 1 to 1 relationship?

Closed this issue · 1 comments

Sorry for the noob question, came across SqlFu and like the look of it so am experimenting.

I have 2 tables:
User
Address

The user table has a foreign key of PostalAddressId.

My classes are:

namespace Entities
{
    [Table("Address", PrimaryKey = "Id", AutoGenerated = true)]
    public class Address
    {
        public int Id { get; set; }
        public string BuildingOrUnitName { get; set; }
        public string NumberAndStreet { get; set; }
        public string Suburb { get; set; }
        public string Town { get; set; }
        public string PostCode { get; set; }
        public string Country { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Updated { get; set; }
    }

    [Table("User", PrimaryKey = "Id", AutoGenerated = true)]
    public class User
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        [ForeignKey("Address", "Id", KeyName = "PostalAddressId", OnDelete = ForeignKeyRelationCascade.Cascade, OnUpdate = ForeignKeyRelationCascade.Cascade)]
        public Address PostalAddress { get; set; }
        public bool RegistrationComplete { get; set; }
        public DateTime? Created { get; set; }
        public DateTime? Updated { get; set; }
    }
}

When I attempt to save the user record using:

        public static Entities.User Save(Entities.User value)
        {
            if ((value.Id == null || value.Id == Guid.Empty) && value.Created == null) value.Created = DateTime.UtcNow;
            if (value.Updated == null) value.Updated = DateTime.UtcNow;

            using (DbConnection db = new SqlFuConnection("Identity"))
            {
                if (value.Id == null || value.Id == Guid.Empty)
                {
                    LastInsertId id = db.Insert(value);
                    value.Id = id.InsertedId<Guid>();
                }
                else
                {
                    db.Update<Entities.User>(value);
                }
            }

            // Return with all populated default values present
            return GetById(value.Id);
        }

I get the following exception:
Additional information: Invalid column name 'PostalAddress'.

What is your best practice suggestion for dealing with this sort of mapping?

Thanks in advance for any guidance.

SqlFu is not (and will never be) an ORM. It uses POCOs as data source/destination. The attributes are used for table creation and by some helpers. That's it. If you want 'real' mapping, you should use an ORM like EF.