C# EF 将记录添加到客户表,其中包含 Zip 表的外键

标签 c# mysql .net entity-framework

我是 Entity Framework 的新手,并开始使用数据库优先方法开发第一个应用程序,我已在ZipTable中添加了所有记录,现在正在努力在中添加记录从 .csv 文件读取数据后的 CustomerTable

客户表(电话[PK]、名字、姓氏、地址、 zip [FK] )< br/> ZipTable( Zip[PK],城市,县 )

//Class Automatically Generated by EF 

public partial class dbzipcode
{
public dbzipcode()
{
    this.dbcustomers = new HashSet<dbcustomer>();
}

    public string ZIP { get; set; }
    public string CITY { get; set; }
    public string COUNTY { get; set; }

    public virtual ICollection<dbcustomer> dbcustomers { get; set; }
}

public partial class dbcustomer
{
    public string PHONE { get; set; }
    public string FIRSTNAME { get; set; }
    public string LASTNAME { get; set; }
    public string ADDRESS { get; set; }

    public string ZIP { get; set; }
    public virtual dbzipcode dbzipcode { get; set; }
}

我已经在数据库中拥有了 ZipCodes 的数据现在,当我尝试在 CustomerTable 中添加数据时,我遇到了 forignkey 错误,我希望如果辅助表中存在相应的 Zip,则应插入 Customer zip 中,否则应抛出异常。

为了实现这一点,我首先在插入每条记录之前从 csv 中读取 Zip 数据。我认为这不是正确的方法,有人可以指出我正确的方向吗?

                    dbcustomer customer = new dbcustomer();
                    customer.PHONE = splits[columnIndexPhoneNumber];
                    customer.FIRSTNAME = splits[columnIndexFirstName];
                    customer.LASTNAME = splits[columnIndexLastName];
                    customer.ADDRESS = splits[columnIndexAddress];
                    customer.ZIP = splits[columnIndexZipCode];

                    //dbzipcode z = new dbzipcode() { ZIP=customer.ZIP};

                    dbzipcode z = ZipCodeDbHandler.GetInstance().GetZipCodeFromDb(splits[columnIndexZipCode]);
                    customer.dbzipcode = z;

最佳答案

您有客户表和 zip 表,

我要记录的新客户的邮政编码在我的邮政编码表中找不到,因此您设置通用邮政编码或无,或者在完整记录之前添加新的邮政编码,这是可以的(没有错误的方法)如果邮政编码表中有完整的邮政编码并且客户不能在此之外,则将是错误的) ,所以选项:记录在客户表中,如果邮政编码未记录在邮政编码表中,则执行异常并要求确认记录邮政编码,否则警报必须输入有效的邮政编码

关于C# EF 将记录添加到客户表,其中包含 Zip 表的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553260/

相关文章:

mysql - 是否可以使用sequelize部分更新行?

c# - 为什么这个 JavaScript 不显示确认框?

c# - Session.Clear 后的 Nhibernate LazyInitializationException

c# - 通过编码表示形式限制 TextBox 中 Text 的长度

mysql - 在 MySQL 中连接多个表以获得不相等的值

c# - 用于从关键字中检索相似词的 API?

.net - WPF 从对象的 DataTable 绑定(bind)到 DataGrid

c# - FFmpeg av_interleaved_write_frame 缓冲

c# - SQL Server 的 IP 地址连接字符串

mysql - 多个 GROUP BY 并按 SUM'd 组值排序